-
Notifications
You must be signed in to change notification settings - Fork 2
/
Queue.java
104 lines (93 loc) · 1.86 KB
/
Queue.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
98
99
100
101
102
103
104
package own;
/*
* Implementation of queues using arrays as an underlying data structure.
* Resizing and efficient space usage.
*/
public class Queue {
private int start;
private String [] q;
private int end;
private int count = 0;
public Queue(){
start = -1;
end = 0;
q = new String[1];
}
private int size(){
return count;
}
public boolean isEmpty(){
return size() == 0;
}
public void enqueue(String value){
if (size() == q.length){
end = q.length;
resize(2 * q.length);
}
if (isEmpty())
start = end;
q[end] = value;
end = (end + 1) % q.length;
count ++;
}
public String dequeue(){
assert (start >=0);
String item = q[start];
count--;
q[start] = null;
start = (start + 1) % q.length;
if (count == q.length / 4){
System.out.println("resize");
resize(q.length / 2);
end = q.length /2;
}
return item;
}
public void resize(int new_size) {
String [] new_array = new String[new_size];
int old_size = q.length;
int i = start;
int limit = (start < end) ? end : old_size;
for (i = start; i < limit; i++) {
new_array[i - start] = q[i];
}
if (end < start) {
for (int j = 0; j < end; j++) {
new_array[i] = q[j];
i++;
}
}
start = 0;
q = new_array;
}
public void printQueue() {
for (String s: q) {
System.out.println(s);
}
}
// Queue client
public static void main(String[] args) {
Queue q = new Queue();
q.enqueue("m");
q.enqueue("i");
q.enqueue("h");
q.enqueue("a");
q.dequeue();
q.dequeue();
q.printQueue();
q.enqueue("bob");
System.out.println();
q.printQueue();
System.out.println(q.dequeue());
System.out.println(q.dequeue());
System.out.println(q.dequeue());
System.out.println(q.size());
q.enqueue("ema");
q.printQueue();
q.enqueue("rob");
q.dequeue();
q.enqueue("taxi");
q.printQueue();
System.out.println(q.size());
}
}