【问题标题】:Why does stack.pop not accept stack.push as parameter?为什么 stack.pop 不接受 stack.push 作为参数?
【发布时间】: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 函数能够处理吗?
  • 阅读ericlippert.com/2014/03/05/how-to-debug-small-programs 了解调试代码的技巧。
  • 当然可以(这就是它编译的原因)。您试图弹出一个空堆栈的事实显然是问题所在,这一点可以通过添加一个变量来保存结果没有任何改变这一事实来确定。

标签: java stack indexoutofboundsexception


【解决方案1】:

问题很可能出在您的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 个内容,然后执行插入操作,那么程序将正常运行。

【讨论】:

    猜你喜欢
    • 2020-06-22
    • 2015-12-15
    • 2022-09-23
    • 1970-01-01
    • 2015-08-21
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多