首页 > 解决方案 > 为什么 stack.pop 不接受 stack.push 作为参数?

问题描述

我正在尝试创建一种方法,以便能够在我的自定义设计堆栈(基于数组构建)中的位置 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();

标签: javastackindexoutofboundsexception

解决方案


问题很可能出在您的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 个内容添加到堆栈中,然后进行插入,则程序将正常工作。


推荐阅读