【发布时间】:2019-09-23 16:32:50
【问题描述】:
我正在尝试创建一个方法,以便能够在我的自定义设计堆栈(基于数组构建)中的位置 n 处插入一个节点。当我在stack.push() 中使用stack.pop() 作为参数时,我得到ArrayIndexOutOfBoundsException: -1。
我尝试将stack.pop(stack.push()) 替换为代表它的变量,但遇到了同样的异常 (ArrayIndexOutOfBoundsException: -1)。
堆栈类
public class Stack {
public Node[] stackList = new Node[12];
int index = 0; //Sets index to 0
public void push(Node node){ //Adds nodes to the top of the stack.
stackList[index] = node;
if (index < (stackList.length - 1)){
index++;
}
}
public Node pop(){ //Removes node from stack.
Node output = stackList[index];
stackList[index] = null;
index--;
return output;
}
public void printStack(){
for (int j = 0; j < stackList.length; j++){
stackList[j].printValue();
}
}
public int size(){
return stackList.length;
}
public void insertNode(int val, int pos, Stack stack){
Stack tmpstack = new Stack();
Node value = new Node();
value.changeValue((val));
int i=0; //Sets index to 0
while(i<pos){
tmpstack.push(stack.pop());
i++;
}
stack.push(value);
while(tmpstack.size() > 0)
stack.push(tmpstack.pop());
}
主类中的方法
public class Main {
public static void main(String[] args){
//Stack
System.out.println("Starting to print the value of the stack:");
Stack s = new Stack();
for (int i = 0; i < 12; i++) {
Node node = new Node();
node.changeValue((i+1));
s.push(node);
}
s.printStack();
s.insertNode(77,5, s); //value, position, stack
s.printStack();
【问题讨论】:
-
你能分享你的 Stack.push() 和 Stack.pop() 代码吗?
-
由于您似乎在使用自定义 Stack 对象,因此只能在不提供相关推送/弹出代码的情况下做出假设。 pop 的返回类型很可能与 push 的参数类型不匹配,反之亦然。此外,您引用了
stack.pop(stack.push())的问题,但这在您提供的代码中不是。 -
由于您添加了一个值,因此您的堆栈大小将增加 1。您确定您的 push 函数能够处理吗?
-
当然可以(这就是它编译的原因)。您试图弹出一个空堆栈的事实显然是问题所在,这一点可以通过添加一个变量来保存结果没有任何改变这一事实来确定。
标签: java stack indexoutofboundsexception