我正在研究 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
}
}
}