next up previous index
Next: List Implementation of Queue Up: Linked Implementations Previous: The ListNode   Index


List Implementation of Stack

Using the ListNode class, the stack can be implemented very simply as shown in Figure 4.1.

Figure 4.1: A list implementation of the Stack interface.
import java.util.NoSuchElementException;

public class StackList implements Stack {

    private ListNode top;

    public StackList() {
        top = null; 
    }

    public boolean isEmpty() {
        return top == null;
    }
  
    public void push(Object item) {
        top = new ListNode(item, top);
    }
  
    public Object pop() {
        if (top == null) {
            throw new NoSuchElementException();
        } else {
            Object item = top.data;
            top = top.next;
            return item;
        }
    }
  
}

There is a single private instance variable top, of type ListNode, corresponding to the head of the list. There is a single constructor which sets top to null. The stack is empty when top == null. An item is pushed onto the stack using
public void push(Object item) {
    top = new ListNode(item, top);
}
The single line of code forming the body of this method needs a word of explanation. On the right, top has its original value, namely a reference to the top of the stack before this push. A new ListNode is created, whose data field is the new item and whose next field is the stack as it was. The variable top is then reassigned to be a reference to this new node.

When the stack consists of [5, 2, 3] it can be pictured as


\begin{picture}(440,50)(40,0)
\put(50,32){\makebox(0,0){\tt top}}
\put(20,20){...
...x (40,40){\tt 3}}
\put(360,0){\framebox (40,40){\Large {$\ast$}}}
\end{picture}
When the stack is popped, 5 is returned and the stack becomes

\begin{picture}(440,50)(100,0)
\put(170,32){\makebox(0,0){\tt top}}
\par\put(14...
...x (40,40){\tt 3}}
\put(360,0){\framebox (40,40){\Large {$\ast$}}}
\end{picture}
In the pop method, it is tempting to write
return top.data;
top = top.next;
meaning that the top data item is returned, and top is then made to refer to the next node. But the method would terminate with the return statement! Doing it the other way round
top = top.next;
return top.data;
means that top.next.data is returned rather than top.data. The solution is to store top.data in a temporary variable item, as shown in the code.


next up previous index
Next: List Implementation of Queue Up: Linked Implementations Previous: The ListNode   Index
Peter Williams 2005-06-07