-
Notifications
You must be signed in to change notification settings - Fork 2
/
ArrayQueue.java
88 lines (76 loc) · 1.88 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
package will.zhang.queue;
/**
* @Author will
* @Date 2018/5/1 0001 下午 7:49
* 实现基本的数组队列
*
* 复杂度分析
* void enqueue(E) O(1) 均摊
* E dequeue() O(n)
* E front() O(1)
* int getSize() O(1)
* boolean isEmpty() O(1)
**/
public class ArrayQueue<E> implements Queue<E> {
//使用上一章实现的动态数组来存放数据
private Array<E> array;
public ArrayQueue(int capacity){
array = new Array<>(capacity);
}
public ArrayQueue(){
array = new Array<>();
}
@Override
public int getSize() {
return array.getSize();
}
@Override
public boolean isEmpty() {
return array.isEmpty();
}
/**
* 获取队列的容量
* @return
*/
public int getCapacity(){
return array.getCapacity();
}
@Override
public void enqueue(E e) {
array.addLast(e);
}
@Override
public E dequeue() {
return array.removeFirst();
}
@Override
public E getFront() {
return array.getFirst();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Queue: ");
builder.append("front [");
builder.append("[");
for (int i = 0; i < array.getSize(); i++) {
builder.append(array.get(i));
if(i != array.getSize() - 1){
builder.append(", ");
}
}
builder.append("] tail");
return builder.toString();
}
public static void main(String[] args) {
ArrayQueue<Integer> queue = new ArrayQueue<>();
for (int i = 0; i < 10; i++) {
queue.enqueue(i);
System.out.println(queue);
if(i % 3 == 2){
queue.dequeue();
System.out.println(queue);
}
}
}
}