我已经在Java中实现了一个非常基本的Stack,它提供了以前从未遇到的奇怪错误。 代码如下: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个元素与下一个适当的/顶部指针集合中的正确的顺序被推动完美。 但是,当我尝试弹出所有元素时,只有它弹出前四(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)
这些错误不会通过引入在推一些打印语句道理给我,而且( )和printStack()来跟踪它开始抛出更多的随机异常。 这些错误对于每次运行都是完全不确定的,并在不同的机器中给出不同的模式。 我用Netbeans调试器追踪了一次完整的运行,发现没有错误!
非常感谢您的帮助! 谢谢!
也许它没有任何关系,但我会声明pop和push方法同步。而且我也会在peek方法中验证top不为空 – BWitched 2012-04-28 10:20:42