我在Java中实现了一个非常基本的Stack,它给出了从未遇到过的奇怪错误。
代码如下:

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();
}
}


我已经进行了彻底的测试,发现push操作可以正确地按顺序使用正确的next / top指针设置来推动所有7个元素。
但是,当我尝试弹出所有元素时,只有它弹出前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++)


因为您的堆栈大小随着每次迭代而减小。

09-28 07:49