Home > Software design >  Stack implementation using LinkedList in java references not working properly
Stack implementation using LinkedList in java references not working properly

Time:04-05

Each time a push operation is called on this stack, the new node is created but the stack just gets null. Please help me with what is wrong with my code. I am messing up with reference variables. When a push operation is called from main method, the top gets null each time. I don't know why is this happening. import java.util.EmptyStackException;

public class LinkedListImplStack {

public LinkedListImplStack() {
    this.top = null;
}
//Node
private static class Node<T> {
    T data;
    Node next;

    public Node(T data) {
        this.data = data;
        this.next = null;
    }
}

// maintain top
private Node top;

//push()
public void push(T data) {
    Node<T> node = new Node(data);
    node.next = top;
     top = node;
}

//pop()
public T pop() {
    if(top == null)
        throw new EmptyStackException();
    T toBePopped = (T) top.data;
    top = top.next;
    return toBePopped;
}

//peek()
public T peek() {
    if(top == null)
        throw new EmptyStackException();
    return (T) top.data;
}

@Override
public String toString() {
    StringBuilder s = new StringBuilder();
    while(top!=null) {
        s.append(top.data   " -> ");
        top = top.next;
    }
    return s.toString();
}
public static void main(String[] args) {
    LinkedListImplStack myStack = new LinkedListImplStack();
    myStack.push(1);
    myStack.push(2);
    myStack.push(3);
    System.out.println(myStack);
    myStack.pop();
    System.out.println(myStack);
    myStack.push("four");
    System.out.println(myStack);
    System.out.println(myStack.peek());
}

}

CodePudding user response:

public String toString() {
    StringBuilder s = new StringBuilder();
    while(top!=null) {
        s.append(top.data   " -> ");
        top = top.next;
    }
    return s.toString();
}

When calling toString(), you move the member variable top pointer along to the end of the stack, effectively nulling the stack; make a copy of top and iterate over that to solve your problem.

CodePudding user response:

In intellij, there is an enable toString() view of an object property, if we disable it, then toString() will be invoked only when we invoke it. Otherwise toString() is invoked each time a method like stack.push() is being called, which makes my stack null due to the incorrect implementation of my toString() method.

The first answer will help with the understanding.

Skipped breakpoint because it happened inside debugger evaluation - Intellij IDEA

  • Related