-
Notifications
You must be signed in to change notification settings - Fork 0
/
MyArrayQueue.java
54 lines (46 loc) · 1.21 KB
/
MyArrayQueue.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
package queue;
/**
* 数组实现的循环队列
*/
public class MyArrayQueue<T> implements IQueue<T> {
private T[] datas; // 存放数据的数组
private int capacity; // 数组容量
private int count = 0; // 计数,用于计算长度
private int top = 0; // 队首位置
private int tail = -1; // 队尾的上一个位置
public MyArrayQueue(int capacity) {
this.capacity = capacity;
this.datas = (T[]) new Object[capacity];
}
@Override
public void offer(T data) {
if (count == capacity)
throw new RuntimeException("队列已满");
tail = (tail + 1) % capacity;
datas[tail] = data;
count++;
}
@Override
public T peek() {
if (isEmpty())
throw new RuntimeException("队列为空");
return datas[top];
}
@Override
public T poll() {
if (isEmpty())
throw new RuntimeException("队列为空");
T res = datas[top];
top = (top + 1) % capacity;
count--;
return res;
}
@Override
public int size() {
return this.count;
}
@Override
public boolean isEmpty() {
return this.count == 0;
}
}