链接列表堆栈丢失最后一项推送到堆栈

时间:2013-03-14 01:58:38

标签: java linked-list stack

我正在处理堆栈的链接列表实现,并且似乎只有一个错误就有我需要的东西。我插入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;        
}  
}

这是我的Main():

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
    }
}
}

1 个答案:

答案 0 :(得分:4)

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

它应该是这样的:

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

当你在这里时,你也可以修复你的窥视()

public T peek(){
    if (isEmpty()) {
        throw new RuntimeException("Stack is empty");
    }   
    return top.data;        
}