0

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

}

2 Answers 2

1
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.

Sign up to request clarification or add additional context in comments.

1 Comment

When i call this method - myStack.push(1); Internally toString() method is being called?? Because i haven't called it until i have pushed 3 elements to stack.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.