-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCircularQueue.java
More file actions
62 lines (56 loc) · 1.34 KB
/
CircularQueue.java
File metadata and controls
62 lines (56 loc) · 1.34 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
package com.fantasy.datastructure.queue;
/**
* 循环队列
*
* <pre>
* author : Fantasy
* version : 1.0, 2020-08-30
* since : 1.0, 2020-08-30
* </pre>
*/
public class CircularQueue {
private String[] mData;
/**
* 队列的容量
*/
private int mSize = 0;
/**
* 队头下标
*/
private int mHead = 0;
/**
* 队尾下标
*/
private int mTail = 0;
public CircularQueue(int capacity) {
mData = new String[capacity];
mSize = capacity;
}
public boolean enqueue(String item) {
if ((mTail + 1) % mSize == mHead) {
// 队满,mTail 指向的位置不存储数据,实际存储的数据个数为 mSize - 1
return false;
}
mData[mTail] = item;
mTail = (mTail + 1) % mSize;
return true;
}
public String dequeue() {
if (mHead == mTail) {
return null;
}
String item = mData[mHead];
mHead = (mHead + 1) % mSize;
return item;
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = mHead; i % mSize != mTail; i++) {
sb.append(mData[i]);
if ((i + 1) % mSize != mTail) {
sb.append(",").append(" ");
}
}
return sb.toString();
}
}