2012-04-28 36 views
0

我已经在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调试器追踪了一次完整的运行,发现没有错误!

非常感谢您的帮助! 谢谢!

+0

也许它没有任何关系,但我会声明pop和push方法同步。而且我也会在peek方法中验证top不为空 – BWitched 2012-04-28 10:20:42

回答

2

首先在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++) 

,因为你的堆栈大小与每个迭代减少。

+0

非常感谢您的回复! – 2012-04-28 10:29:42

+0

你的两点都是正确的,并解决了问题。对于第一点,位置从1移动到s。getSize()是可以理解的,但是在那种情况下,错误应该在最后一次迭代时抛出,当它超出界限时。但是从某些输出可以看出,NullPointerException错误出现在随机迭代中,其中一些出现在开始和中间迭代中。为什么这样? – 2012-04-28 10:33:17

+0

我真的不知道为什么异常堆栈跟踪开始在抛出异常之前打印。 – 2012-04-28 10:39:49

0
for (int i=0; i<s.getSize(); i++) 

导致堆栈大小减小用于每个弹出,我将每个流行增加。当它完成4次弹出时,堆栈大小等于i的值。因此,打印堆栈停在中间。

更换上面循环具有以下

for (; !s.isEmpty();) 

将解决这个问题。

0

printStack()失败,因为您没有检查n为空。以下代码修复了此问题。

`public void printStack(){ Node n = this.top; int pos = this.getSize();

System.out.println("Stack Size is " + pos); 
    while(n!=null) { 
     System.out.println("Position: " + pos + " Element: " + n.data); 
      n = n.next; 
     pos--; 
    } 
}`