0
我需要使用動態數組來實現一個堆棧數組,我必須創建自己的數組。Java中的堆棧和動態數組實現
這裏是我的動態數組:
import java.util.Arrays;
public class Array {
public int[] dynArray;
int counter = 0;
public void create(int n) {
dynArray = new int[n];
}
public void doubleSize() {
int currentSize = dynArray.length;
int newSize = currentSize*2;
dynArray = Arrays.copyOf(dynArray, newSize);
}
private void halfSize() {
int currentSize = dynArray.length;
int newSize = currentSize/2;
dynArray = Arrays.copyOf(dynArray, newSize);
}
public void add(int x) {
dynArray[counter] = x;
counter++;
float ratio = (float) counter/(float) dynArray.length;
if (ratio == 1) {
doubleSize();
}
}
public int rem() {
int last = dynArray[counter-1];
dynArray[counter-1] = 0;
counter--;
float ratio = (float) counter/(float) dynArray.length;
if (ratio <= 0.25) {
halfSize();
}
return last;
}
public int get(int i) {
if(!(check(i))) {
//System.out.print("Cannot be added");
return i;
}
else return dynArray[i];
}
public void put(int x, int y) {
float ratio = (float) counter/(float) dynArray.length;
if (ratio ==1) {
doubleSize();
}
if(!check(y)) {
System.out.println("No such index, nothing added to "+y);
} else {
dynArray[y] = x;
}
}
public int len() {
return dynArray.length;
}
public boolean check(int index) {
if(index <0 || index >=dynArray.length) {
return false;
} else {
return true;
}
}
public static void main(String[] args) {
Array dm = new Array();
dm.create(5);
System.out.println("Current array length "+dm.len());
dm.add(5);
dm.add(4);
dm.add(3);
dm.add(1);
dm.add(2);
System.out.println("Current array length "+dm.len());
dm.rem();
dm.rem();
System.out.println("Current array length "+dm.len());
dm.rem();
System.out.println("Current array length "+dm.len());
dm.rem();
System.out.println("Current array length "+dm.len());
}
}
這裏是我的籌碼代碼:
public class Stack {
private static Array a;
public void create() {
a = new Array();
}
void push(int x) {
a.add(x);
}
int pop() {
return a.rem();
}
boolean isEmpty() {
return a.len() == 0;
}
public static void main(String[] args) {
Stack stack = new Stack();
stack.create();
stack.push(1);
/*int k = 1;
stack.push(2*k);
stack.push(2*k+1);
stack.push(2*k+2);
for (int i = 0; i<40; i++) {
System.out.println(stack.pop());
}*/
}
}
當我寫stack.push(1)
在Stack.java
主,它給我的地方說:a.add(x)
行了NullPointerException
。我不明白爲什麼會發生這種異常。
你太快了:) – 2014-11-04 11:22:55
修正了它!非常感謝你 - 現在我可以繼續我的工作。我堅持了3個小時:) – e4n 2014-11-04 12:00:22
@ e4n不客氣! – Eran 2014-11-04 12:05:08