编程语言
首页 > 编程语言> > java-链​​接列表堆栈丢失最后一个压入堆栈的项目

java-链​​接列表堆栈丢失最后一个压入堆栈的项目

作者:互联网

我正在开发堆栈的链表,并且似乎只有一个错误就可以满足我的需要.我正在插入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
    }
}
}

解决方法:

似乎您正在弹出顶部,然后在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;        
}  

标签:stack,linked-list,java
来源: https://codeday.me/bug/20191031/1973426.html