TheA
TheA

Reputation: 11

How to make pop() method to return and delete the second element in the stack?

I wrote an implementation of a Stack using Linked Nodes, but I want to add a method next to pop() that will remove the second item of the Linkedstack not the top item. I know that the point of implementing a stack is to only be able to remove the top item, but I need to implement this method.

This is the code for the pop() method I already have:

public T pop() {
    T top = peek();
    if (topNode != null)
        topNode = topNode.getNextNode();
    return top;
}

So what I want to do is let a new node point to the second element in the chain so I can return its value and then make topNode point to the first node as it is and then have that first node pointing to the third node in the chain so the second is deleted.

Upvotes: 1

Views: 1309

Answers (1)

Eran
Eran

Reputation: 393811

You can do two regular pop operations to remove the first two elements, and then push the first element back to the top of the stack and return the second element that was popped.

Upvotes: 3

Related Questions