-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArrayQueue.java
97 lines (88 loc) · 2.37 KB
/
ArrayQueue.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
public class ArrayQueue<A> {
private int f = 0, b = 0;
private A[] queueArray;
public static final int CAPACITY=1000;
public ArrayQueue() {
this(CAPACITY);
}
@SuppressWarnings({"unchecked"})
public ArrayQueue(int capacity)
{ // constructs stack with given capacity
queueArray = (A[]) new Object[capacity];
}
public void enqueue(A data)
{
// check if queue is full
if (CAPACITY == b) {
System.out.printf("Queue is already full!");
return;
}
// add to back
else {
queueArray[b] = data;
b++;
}
return;
}
public void dequeue()
{
// if stack empty cant delete
if (f == b) {
System.out.printf("Queue is already empty!");
return;
}
// move the queue
else {
for (int i = 0; i < b - 1; i++) {
queueArray[i] = queueArray[i + 1];
}
// clear the back
if (b < CAPACITY) {
queueArray[b] = null;
}
// back decreases
b--;
}
return;
}
public String toString()
{
int i;
String s="Queue Contains";
if (f == b) {
s+="Nothing!";
return s;
}
// add each queue element
for (i = f; i < b; i++) {
s+=" "+ queueArray[i];
}
return s;
}
public A front()
{
if (f == b) {
System.out.println("Queue is empty!");
return null;
}
return queueArray[f];
}
public static void main (String[] args)
{
LinkedQueue<Integer> testQueue = new LinkedQueue<Integer>();
System.out.println(testQueue.toString());
testQueue.enqueue(400);
testQueue.enqueue(100);
testQueue.enqueue(200);
System.out.println(testQueue.isEmpty());
testQueue.dequeue();
testQueue.enqueue(300);
System.out.println(testQueue.size());
System.out.println(testQueue.toString());
while(!testQueue.isEmpty())
{
System.out.println("Dequeued: "+testQueue.dequeue());
}
System.out.println(testQueue.isEmpty());
}
}