-
Notifications
You must be signed in to change notification settings - Fork 28
/
QueueArray.java
86 lines (68 loc) · 1.38 KB
/
QueueArray.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
package ds_004_stacks_and_queues;
public class QueueArray<T> {
private final static int DEFAULT_CAPACITY = 8;
private int capacity;
private T[] collection;
private int front;
private int back;
private int size;
public QueueArray(int capacity) {
this.capacity = capacity;
front = back = -1;
collection = (T[])new Object[this.capacity];
}
public QueueArray() {
this(DEFAULT_CAPACITY);
this.capacity = DEFAULT_CAPACITY;
}
public void enqueue(T value){
if(isEmpty()) {
front = 0;
back = -1;
}
collection[++back] = value;
size++;
}
public T dequeue() {
if(isEmpty()) {
return null;
}
T value = collection[front];
collection[front] = null;
front++;
size--;
return value;
}
public T peek() {
if(isEmpty()) {
return null;
}
return collection[front];
}
// trivial methods
public int size() {
return size;
}
public boolean isEmpty() {
return size == 0 ? true : false;
}
public void print() {
System.out.print("Queue: ");
if(isEmpty()) {
System.out.print("EMPTY");
} else {
for(int i = front; i <= back; i++) {
System.out.printf("%s ", collection[i]);
}
}
System.out.print("\n");
}
public int capacity() {
return capacity;
}
public void state() {
System.out.println("State;");
System.out.println("\tIsEmpty: " + isEmpty());
System.out.println("\tSize : " + size);
}
}