我试图将数组调整为"push"方法,但在输出中数字"6"不存在。
有线索吗?
public void push(int value) {
if (size != maxSize){
top++;
stackArray[top] = value;
size++;
}else if (size == maxSize){
stackArray = Arrays.copyOf(stackArray, size * 2);
maxSize = size * 2;
size++;
}else{
throw new RuntimeException();
}
}
Pop方法
public int pop() {
if (size != 0){
size--;
return stackArray[top--];
} else {
throw new RuntimeException();
}
}
我在那堆上放了一些元素
Stack theStack= new Stack(5);
theStack.push(1);
theStack.push(2);
theStack.push(3);
theStack.push(4);
theStack.push(5);
theStack.push(6);
theStack.push(7);
System.out.println(theStack.pop());
System.out.println(theStack.pop());
System.out.println(theStack.pop());
System.out.println(theStack.pop());
System.out.println(theStack.pop());
System.out.println(theStack.pop());
然后我得到了这个
75.4.3.2.1
在size == maxSize
的情况下,调整数组大小后不添加6。请将你的方法修改为这样。
现在,您将首先调整大小(如果需要)。然后像往常一样插入。
public void push(int value) {
// resize if required
if (size == maxSize){
stackArray = Arrays.copyOf(stackArray, size * 2);
maxSize = size * 2;
}
// then do the addition to the array stuff
if (size != maxSize){
top++;
stackArray[top] = value;
size++;
} else {
throw new RuntimeException();
}
}