3

I am working on a Linked List implementation of a Stack, and seem to have what I need with only one error. I am inserting 3 strings, but before the 3rd string is popped, I get a NullPointerException.

In running debug I found that this missing value is being 'popped' off this list but it seems like it is not counted...meaning it is missing from the stack, not printed to the console, and the list does one more iteration at which point the NullPointerException is thrown because the last value was already popped. Can someone tell me how to get all of my values to print to console?

Here is my LinkedListStack Class:

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

Here is my 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
    }
}
}
Chris
  • 934
  • 1
  • 17
  • 38

1 Answers1

4

It appears you're popping the top off and then reading the new top's value in the pop() method

It should look like this:

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

While you're at it, you might as well fix your peek()

public T peek(){
    if (isEmpty()) {
        throw new RuntimeException("Stack is empty");
    }   
    return top.data;        
}  
Michael Deardeuff
  • 10,386
  • 5
  • 51
  • 74