Java Reference
In-Depth Information
Similarly, we write pop as follows. Since only NodeData should know the type of data being defined, we will let it
tell us what is the rogue value.
public NodeData pop() {
if (this.empty())return NodeData.getRogueValue();
NodeData hold = top.data;
top = top.next;
return hold;
} //end pop
The observant reader will notice that all we have done so far is change int to NodeData in Node , push , and pop .
If we want to implement a stack of integers, we can define the NodeData class as follows. It is the same as before
with the addition of the accessor getData() .
public class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public int getData() {return num;}
public static NodeData getRogueValue() {return new NodeData(-999999);}
public int compareTo(NodeData nd) {
if (this.num == nd.num) return 0;
if (this.num < nd.num) return -1;
return 1;
}
public String toString() {
return num + " ";
//" " needed to convert num to a string; may also use "" (empty string)
}
} //end class NodeData
Despite all these changes to Node , Stack , and NodeData , the class StackTest of Programs P4.1 and P4.2 will work
like before if we just change S.push(n) to S.push(new NodeData(n)) and S.pop() to S.pop().getData() , as shown
in Program P4.3. Note that, for this program, we won't need compareTo and toString from the NodeData class, so they
are omitted. As usual, we omit public from the class headers (except StackTest ) so that the entire program can be
kept in one file.
Program P4.3
import java.util.*;
public class StackTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Stack S = new Stack();
System.out.printf("Enter some integers ending with 0\n");
 
Search WWH ::




Custom Search