Java Reference
In-Depth Information
4.3 A General Stack Type
To simplify our presentation, we have worked with a stack of integers. We remind you of those places that are tied to
the decision to use integers.
Node , we declare an int called num .
In the declaration of
push , we pass an int argument.
In
pop , we return an int result.
This means that if we need a stack of characters, say, we will have to change int to char in all of these places.
Similar changes will have to be made for stacks of other types.
It would be nice if we could minimize the changes needed when a different type of stack is required. We now
show how this could be done.
First, we define Node as follows:
In
class Node {
NodeData data;
Node next;
public Node(NodeData d) {
data = d;
next = null;
}
} //end class Node
The data at a node consists of the general type, NodeData . When the user defines the NodeData class, he will
decide what kind of items will be stored on the stack.
The Stack class starts off the same as before:
public class Stack {
Node top = null;
public boolean empty() {
return top == null;
}
...
But now, push will require a NodeData argument and can be written as follows:
public void push(NodeData nd) {
Node p = new Node(nd);
p.next = top;
top = p;
} //end push
 
Search WWH ::




Custom Search