Reputation: 11
I am struggling to figure this out - I need to implement a method: public int remove(int n) where I remove the top most n entries from my stack. Any suggestions on where I can start to tackle this would be greatly appreciated.
Here is the code provided where I need to implement this remove() method.
public class LinkedStack<T> implements StackInterface<T>
{
private Node topNode; // references the first node in the chain
public LinkedStack()
{
topNode = null;
} // end default constructor
public void push(T newEntry)
{
Node newNode = new Node(newEntry, topNode); topNode = newNode;
} // end push
public T peek()
{
T top = null;
if (topNode != null)
top = topNode.getData();
return top;
} // end peek
public T pop()
{
T top = peek();
if (topNode != null)
topNode = topNode.getNextNode();
return top;
} // end pop
public boolean isEmpty() {
return topNode == null;
}
public void clear() {
topNode = null;
}
private class Node
{
private T data; // entry in stack
private Node next; // link to next node
private Node(T dataPortion)
{
this(dataPortion, null);
} // end constructor
private Node(T dataPortion, Node nextNode)
{
data = dataPortion;
next = nextNode;
} // end constructor
private T getData()
{
return data;
} // end getData
private void setData(T newData)
{
data = newData;
} // end setData
private Node getNextNode()
{
return next;
} // end getNextNode
private void setNextNode(Node nextNode)
{
next = nextNode;
} // end setNextNode
} // end Node
} // end LinkedStack
Upvotes: 1
Views: 865
Reputation: 37845
The trivial solution is just to call this.pop()
n
times. For this, you need to use a loop.
Seems like your homework, so I'm not going to show a code example.
Upvotes: 1