java - 为什么 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();
解决方案
问题很可能出在您的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 个内容添加到堆栈中,然后进行插入,则程序将正常工作。
推荐阅读
- asp.net-core-mvc - ASP.NET Core MVC 在局部视图/ViewComponent 中提交表单
- c++ - 在代码块 (C++) 中调试时,我可以选择跳过所有打开的内部库调用和函数吗?
- python - 三元图作为子图
- git - 如何使用 git diff 作为 difftool?
- python - Python + Scrapy + JSON + XPath:如何使用 Scrapy 抓取 JSON 数据
- unity3d - Unity offscreen target indicator-how to show the way to an object with a specific tag?
- css - 我找不到适用于此滑块的 css 类
- model-checking - NuSMV:如何排除可能的下一个状态
- javascript - 在不使用多个循环的情况下按标题查找重复数组
- r - 在一行中搜索 r 中的一系列值