3

我正在研究 Stack 的 Linked List 实现,并且似乎只有一个错误有我需要的东西。我正在插入 3 个字符串,但在弹出第 3 个字符串之前,我得到了 NullPointerException。

在运行调试时,我发现这个缺失值正在从这个列表中“弹出”,但它似乎没有被计算在内......这意味着它从堆栈中丢失,没有打印到控制台,并且列表在由于最后一个值已经弹出,因此抛出 NullPointerException 。有人可以告诉我如何将我的所有值打印到控制台吗?

这是我的 LinkedListStack 类:

public class LinkedListStack <T>{  
private LinkedListStackNode<T> top;
public T data; 

class LinkedListStackNode<T> {        
    private T data;      //LINE 8
    private LinkedListStackNode<T> next; 

    public LinkedListStackNode(T data, LinkedListStackNode<T> next) {                       
        this.data = data;            
        this.next = next;
    }
}   
public void stack(){
    top = null;
}
public boolean isEmpty(){
    return top == null;
}
public void push (T t){
    top = new LinkedListStackNode<T> (t, top);
}
public T pop (){
    if (isEmpty()){
        System.out.println("The stack is empty!");
    }
    else{
        top = top.next;
    }
    return top.data; //Line 32
}
public T peek(){
    if (isEmpty()){
        System.out.println("Stack is Empty");
    }   
    return top.data;        
}  
}

这是我的主要():

public class StacksAndQsMain {
  public static void main(String[] args) {
           ...snipped code to condense (not part of this implementation)...

    //LinkedList Implementation
    LinkedListStack<String> lls = new LinkedListStack<>();

    String s3 = "Tonight"; //this does not print but is removed from Stack
    String s4 = "We Conqure"; //prints fine
    String s5 = "Stacks"; //prints fine

    lls.push(s5);
    lls.push(s4);
    lls.push(s3);

    while (!lls.isEmpty()){

        System.out.println(lls.pop()); //LINE 32
    }
}
}
4

1 回答 1

4

看来您正在弹出顶部,然后在 pop() 方法中读取新顶部的值

它应该如下所示:

public T pop (){
   if (isEmpty()){
       throw new RuntimeException("Stack is empty");
   }
   else{
       T ret = top.data;
       top = top.next;
       return ret;
   }
}

当你在它的时候,你不妨修复你的 peek()

public T peek(){
    if (isEmpty()) {
        throw new RuntimeException("Stack is empty");
    }   
    return top.data;        
}  
于 2013-03-14T02:03:56.717 回答