-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArrayQueue.java
More file actions
71 lines (63 loc) · 1.53 KB
/
ArrayQueue.java
File metadata and controls
71 lines (63 loc) · 1.53 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
package com.fantasy.datastructure.queue;
/**
* 顺序队列
*
* <pre>
* author : Fantasy
* version : 1.0, 2020-08-30
* since : 1.0, 2020-08-30
* </pre>
*/
public class ArrayQueue {
private String[] mData;
/**
* 队列的容量
*/
private int mSize = 0;
/**
* 队头下标
*/
private int mHead = 0;
/**
* 队尾下标
*/
private int mTail = 0;
public ArrayQueue(int capacity) {
mData = new String[capacity];
mSize = capacity;
}
public boolean enqueue(String item) {
// mTail == mSize,表示队列末尾没有空间了
if (mTail == mSize) {
// mTail == mSize && mHead == 0,表示整个队列都占满了
if (mHead == 0) {
return false;
}
// 数据搬移
for (int i = mHead; i < mTail; i++) {
mData[i - mHead] = mData[i];
}
// 搬移完之后重新更新 mHead 和 mTail
mTail -= mHead;
mHead = 0;
}
mData[mTail++] = item;
return true;
}
public String dequeue() {
if (mHead == mTail) {
return null;
}
return mData[mHead++];
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (int i = mHead; i < mTail; i++) {
sb.append(mData[i]);
if (i != mTail - 1) {
sb.append(',').append(' ');
}
}
return sb.toString();
}
}