-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularArrayQueue.java
More file actions
executable file
·122 lines (100 loc) · 2.82 KB
/
Copy pathCircularArrayQueue.java
File metadata and controls
executable file
·122 lines (100 loc) · 2.82 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
package com.example.arrayQueue;
import com.example.exceptions.EmptyCollectionException;
import com.example.interfaces.QueueADT;
public class CircularArrayQueue<T> implements QueueADT<T> {
private static final int DEFAULT_CAPACITY = 5;
private int count, front, rear;
private T[] queue;
public CircularArrayQueue(int initialCapacity) {
this.count = 0;
this.front = 0;
this.rear = 0;
this.queue = (T[]) new Object[initialCapacity];
}
public CircularArrayQueue() {
this(DEFAULT_CAPACITY);
}
private boolean isFull() {
return this.queue.length == this.size();
}
private void expandCapacity() {
T[] aux = (T[]) new Object[this.queue.length * 2];
int itr = this.front;
for (int j = 0; j < this.count; j++) {
aux[j] = this.queue[itr];
itr = (itr + 1) % this.queue.length;
}
this.queue = aux;
this.front = 0;
this.rear = this.count;
}
/**
* {@inheritDoc }
*/
@Override
public void enqueue(T element) {
if (isFull()) {
expandCapacity();
}
this.queue[this.rear] = element;
this.rear = (this.rear + 1) % this.queue.length;
this.count++;
}
/**
* {@inheritDoc }
*/
@Override
public T dequeue() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
T removed = this.queue[this.front];
this.queue[this.front] = null;
this.front = (this.front + 1) % this.queue.length;
this.count--;
return removed;
}
/**
* {@inheritDoc }
*/
@Override
public T first() throws EmptyCollectionException {
if (isEmpty()) {
throw new EmptyCollectionException(EmptyCollectionException.EMPTY_COLLECTION);
}
return this.queue[this.front];
}
/**
* {@inheritDoc }
*/
@Override
public boolean isEmpty() {
return this.count == 0;
}
/**
* {@inheritDoc }
*/
@Override
public int size() {
return this.count;
}
protected String Print() {
StringBuilder s = new StringBuilder();
int itr = this.front;
while (itr != this.rear) {
s.append(this.queue[itr]).append(" ");
itr = (itr + 1) % this.queue.length;
}
s.append("\n");
return s.toString();
}
//Apenas para ver melhor o que está a acontecer
protected void printAll() {
for (T t : this.queue) {
System.out.println(t);
}
System.out.println("Lengh: " + this.queue.length);
System.out.println("front: " + this.front);
System.out.println("rear: " + this.rear);
}
}