我在 Java 中实现了一个非常基本的堆栈,它给出了以前从未遇到过的奇怪错误。 代码如下:
public class Stack {
Node top;
int size;
public Stack() {top=null; size=0;}
public int pop() {
if(top!=null) {
int item = top.data;
top = top.next;
size--;
return item;
}
return -1;
}
public void push(int data) {
Node t = new Node(data);
t.next = this.top;
this.top = t;
size++;
}
public boolean isEmpty() {
return size<=0 ;
}
public int getSize() {
return size;
}
public int peek() {
return top.data;
}
public void printStack() {
Node n = this.top;
int pos = this.getSize();
while(pos>=0) {
System.out.println("Position: " + pos + " Element: " + n.data);
if(pos>0) {
n = n.next;
}
pos--;
}
}
}
class Node {
public int data;
public Node next;
Node(int d) {data=d; next=null;}
public int getData() {return data;}
}
class Tester {
public static void main(String[] args) {
Stack s = new Stack();
s.push(9);s.push(2);s.push(7);s.push(3);s.push(6);s.push(4);s.push(5);
System.out.println("Size is: " + s.getSize());
//s.printStack();
for (int i=0; i<s.getSize(); i++) {
System.out.print(s.pop()+ " ");
}
System.out.println();
}
}
我已经进行了彻底的测试,发现推送操作可以完美地工作,所有 7 个元素都可以通过正确的下一个/顶部指针设置以正确的顺序推送。 但是,当我尝试弹出所有元素时,它只会弹出 top-4 (5-4-6-3),留下其他元素。 然后,我尝试使用上述方法执行 printStack,但它给出了随机 NullPointerException 错误,如下所示:
run:
Position: 7 Element: 5
Position: 6 Element: 4
Position: 5 Element: 6
Position: 4 Element: 3
Exception in thread "main" java.lang.NullPointerException
Position: 3 Element: 7
Position: 2 Element: 2
at Stack.printStack(Stack.java:58)
Position: 1 Element: 9
at Tester.main(Stack.java:95)
Java Result: 1
BUILD SUCCESSFUL (total time: 0 seconds)
这些错误对我来说没有意义,而且通过在push()和printStack()中引入更多的打印语句来跟踪它开始抛出更多随机异常。 每次运行的错误都是完全不确定的,并且在不同的机器上给出不同的模式。 我已经使用 Netbeans 调试器跟踪了一次完整的运行,没有发现任何错误!
非常感谢您的帮助! 谢谢!
最佳答案
首先在 printStack()
方法中:
while (pos > 0) {
而不是
while (pos >= 0) {
因为你的 0 位置始终为 null
在主要部分:
int size = s.getSize();
for (int i = 0; i < size; i++)
而不是
for (int i = 0; i < s.getSize(); i++)
因为你的堆栈大小随着每次迭代而减小。
关于java - Java 中的简单堆栈实现不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10362499/