为什么stack.pop不接受stack.push作为参数?

问题描述 投票:-1回答:1

我正在尝试创建一个方法,以便能够在我的自定义设计堆栈(基于数组)中的位置n处插入一个节点。当我在stack.pop()中使用stack.push()作为参数时,会得到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();
java stack indexoutofboundsexception
1个回答
0
投票

最有可能是您的Stack类中的问题在这里:

public Node[] stackList = new Node[12];

您可以在堆栈中放入的物品数量上限为12。

您的主程序添加了12个项目,打印堆栈,然后尝试插入一个项目。在您的push方法中,您需要执行以下操作:

public void push(Node node){ //Adds nodes to the top of the stack.
    stackList[index] = node; 
    if (index < (stackList.length - 1)){ 
        index++;
    }
}

将12个项目添加到堆栈后,index等于12。因此,第一行代码stackList[index] = node;尝试更新stackList[12]。这超出了数组的范围(有效索引是0到11)。

我敢打赌,如果您将主循环更改为仅将11个内容添加到堆栈中,然后执行插入操作,程序将正常工作。

© www.soinside.com 2019 - 2024. All rights reserved.