forked from biblelamp/JavaExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathqueue.java
More file actions
80 lines (68 loc) · 2.25 KB
/
queue.java
File metadata and controls
80 lines (68 loc) · 2.25 KB
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
72
73
74
75
76
77
78
79
80
/**
* Book: Data Structures and Algorithms in Java, by Robert LaFore
* Chapter 4:
* queue.java
* demonstrates queue
* to compile this code: javac queue.java
* to run this program: java QueueApp
*/
class Queue {
private int maxSize;
private long[] queArray;
private int front;
private int rear;
private int nItems;
public Queue(int s) { // constructor
maxSize = s;
queArray = new long[maxSize];
front = 0;
rear = -1;
nItems = 0;
}
public void insert(long j) { // put item at rear of queue
if (rear == maxSize-1) // deal with wraparound
rear = -1;
queArray[++rear] = j; // increment rear and insert
nItems++; // one more item
}
public long remove() { // take item from front of queue
long temp = queArray[front++]; // get value and incr front
if (front == maxSize) // deal with wraparound
front = 0;
nItems--; // one less item
return temp;
}
public long peekFront() { // peek at front of queue
return queArray[front];
}
public boolean isEmpty() { // true if queue is empty
return (nItems==0);
}
public boolean isFull() { // true if queue is full
return (nItems==maxSize);
}
public int size() { // number of items in queue
return nItems;
}
} // end class Queue
class QueueApp {
public static void main(String[] args) {
Queue theQueue = new Queue(5); // queue holds 5 items
theQueue.insert(10); // insert 4 items
theQueue.insert(20);
theQueue.insert(30);
theQueue.insert(40);
theQueue.remove(); // remove 3 items
theQueue.remove(); // (10, 20, 30)
theQueue.remove();
theQueue.insert(50); // insert 4 more items
theQueue.insert(60); // (wraps around)
theQueue.insert(70);
theQueue.insert(80);
while (!theQueue.isEmpty()) { // remove and display all items
long n = theQueue.remove(); // (40, 50, 60, 70, 80)
System.out.print(n + " ");
}
System.out.println("");
}
}