Using the ListNode class, the stack can be implemented very simply as shown in Figure 4.1.
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;
}
}
}
|
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
When the stack is popped, 5 is returned and the stack becomes
![]()
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.