-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDynamicArrayQueue.java
More file actions
68 lines (58 loc) · 1.39 KB
/
DynamicArrayQueue.java
File metadata and controls
68 lines (58 loc) · 1.39 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
package ds.queue;
/**
* @author xiangdotzhaoAtwoqutechcommacom
* @date 2019/11/19
* <p>
* 动态数组实现的队列
*/
public class DynamicArrayQueue implements IQueue {
private String[] items;
private int n;
private int head = 0;
private int tail = 0;
public DynamicArrayQueue(int capacity) {
items = new String[capacity];
n = capacity;
}
public static void main(String[] args) {
DynamicArrayQueue queue = new DynamicArrayQueue(3);
queue.enqueue("a");
queue.enqueue("b");
queue.enqueue("c");
queue.printAll();
queue.dequeue();
queue.printAll();
}
@Override
public boolean enqueue(String item) {
if (tail == n) {
if (head == 0) {
return false;
}
for (int i = head; i < tail; i++) {
items[i - head] = items[i];
}
tail -= head;
head = 0;
}
items[tail] = item;
tail++;
return true;
}
@Override
public String dequeue() {
if (head == tail) {
return null;
}
String ret = items[head];
head++;
return ret;
}
@Override
public void printAll() {
for (int i = head; i < tail; i++) {
System.out.print(items[i] + " ");
}
System.out.println();
}
}