Java Reference
In-Depth Information
while (n != 0) {
S.push(n);
n = in.nextInt();
}
System.out.printf("\nNumbers in reverse order\n");
while (!S.empty())
System.out.printf("%d ", S.pop());
System.out.printf("\n");
} //end main
} //end StackTest
class Node {
int data;
Node next;
public Node(int d) {
data = d;
next = null;
}
} //end class Node
class Stack {
final static int RogueValue = -999999;
Node top = null;
public boolean empty() {
return top == null;
}
public void push(int n) {
Node p = new Node(n);
p.next = top;
top = p;
} //end push
public int pop() {
if (this.empty()) return RogueValue; //a symbolic constant
int hold = top.data;
top = top.next;
return hold;
} //end pop
} //end class Stack
The following shows a sample run of Program P4.2. As expected, it works in an identical manner to Program P4.1.
Enter some integers ending with 0
1 2 3 4 5 6 7 8 9 0
Numbers in reverse order
9 8 7 6 5 4 3 2 1
Search WWH ::




Custom Search