Consider a linked implementation of a Stack. Implement the pop() method below. Assume a typical singly linked node, with an instance variables data and next.
public class LinkedStack<T> implements Stack<T>
{
private Node<T> head;
public LinkedStack() {
head = new Node<T>();
}
// pops the top item off the stack
// returning the popped value
// throw an EmptyStackException if there are no
// items in the stack
public T pop() {
// write your implementation below
}
}
SOLUTION :- pop() method for LinkedStack
import java.util.NoSuchElementException;
public class LinkedStack<T> implements Stack<T> {
// field (s ) of the LinkedStack class
private Node top;
// private class of Node data
private class Node {
// field (s ) of the Node class
T elt;
Node next;
// constructor of the Node class
Node(T elt, Node next) {
this.elt = elt;
this.next = next;
}
}
// returns true if the Stack is empty
public boolean isEmpty() {
return (top == null);
}
// pops the top element off the stack
// throws a NoSuchElementException if the stack is empty
public T pop() {
if (this.isEmpty())
throw new NoSuchElementException();
Node t = top;
top = t.next;
return t.elt;
}
}
Get Answers For Free
Most questions answered within 1 hours.