Java Reference
In-Depth Information
if (topNode != null )
top = topNode.getData();
return top;
} // end peek
6.5
Removing the top. We pop, or remove, the top entry in the stack by setting topNode to the refer-
ence in the first node. Thus, topNode will reference what was the second node in the chain, as
Figure 6-3 shows. Moreover, the original first node will no longer be referenced, so it will be deal-
located. Since we also want the operation to return the stack's top entry before it is removed, the
method pop has the following implementation:
public T pop()
{
T top = peek();
if (topNode != null )
topNode = topNode.getNextNode();
return top;
} // end pop
This operation also is O(1).
FIGURE 6-3
The stack (a) before and (b) after the first node in the chain is
deleted
Chain
(a)
topNode
Top entry of stack
Stack
(b)
topNode
Returned to client
top
Stack
 
Search WWH ::




Custom Search