Java Reference
In-Depth Information
To use the Queue class, a user needs to declare only what he wants NodeData to be. To illustrate, suppose he wants
a queue of integers. He can define NodeData as follows:
public class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public int getIntData() {return num;}
} //end class NodeData
Previously, we wrote Program P4.7 which reads an integer and prints its digits in reverse order. We now rewrite it
as Program P4.8 using our new Node , Queue , and NodeData classes.
Program P4.8
import java.util.*;
public class QueueTest {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Queue Q = new Queue();
System.out.printf("Enter a positive integer: ");
int n = in.nextInt();
while (n > 0) {
Q.enqueue(new NodeData(n % 10));
n = n / 10;
}
System.out.printf("\nDigits in reverse order: ");
while (!Q.empty())
System.out.printf("%d", Q.dequeue().getIntData());
System.out.printf("\n");
} //end main
} //end QueueTest
class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public int getIntData() {return num;}
} //end class NodeData
class Node {
NodeData data;
Node next;
Search WWH ::




Custom Search