/
P4_8QueueTest.java
71 lines (60 loc) · 1.92 KB
/
P4_8QueueTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
//Program P4.8
import java.util.*;
public class P4_8QueueTest {
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 P4_8QueueTest
class NodeData {
int num;
public NodeData(int n) {
num = n;
}
public int getIntData() {return num;}
} //end class NodeData
class Node {
NodeData data;
Node next;
public Node(NodeData d) {
data = d;
next = null;
}
} //end class Node
class Queue {
Node head = null, tail = null;
public boolean empty() {
return head == null;
}
public void enqueue(NodeData nd) {
Node p = new Node(nd);
if (this.empty()) {
head = p;
tail = p;
}
else {
tail.next = p;
tail = p;
}
} //end enqueue
public NodeData dequeue() {
if (this.empty()) {
System.out.printf("\nAttempt to remove from an empty queue\n");
System.exit(1);
}
NodeData hold = head.data;
head = head.next;
if (head == null) tail = null;
return hold;
} //end dequeue
} //end class Queue