-
Notifications
You must be signed in to change notification settings - Fork 0
/
622. 设计循环队列.java
129 lines (114 loc) · 2.65 KB
/
622. 设计循环队列.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
/**
* 没有第二次代码的逻辑好
*/
class MyCircularQueue {
private int[] circularQueue;
private int front;
private int rear;
private int length;
private int maxSize;
public MyCircularQueue(int k) {
maxSize = k;
length = 0;
front = 0;
rear = 0;
circularQueue = new int[maxSize];
}
public boolean enQueue(int value) {
if(length >= maxSize){
return false;
}
circularQueue[rear++] = value;
rear %= maxSize;
length++;
return true;
}
public boolean deQueue() {
if(length <= 0){
return false;
}
front++;
front %= maxSize;
length--;
return true;
}
public int Front() {
if(length <= 0){
return -1;
}
return circularQueue[front];
}
public int Rear() {
if(length <= 0){
return -1;
}
int rearIndex = (rear - 1 + maxSize) % maxSize;
return circularQueue[rearIndex];
}
public boolean isEmpty() {
return length == 0;
}
public boolean isFull() {
return length == maxSize;
}
}
/**
* 复习,发现代码逻辑比第一次写的更优
*/
class MyCircularQueue {
int[] circularQueue;
int front;
int rear;
int curSize;
int maxSize;
public MyCircularQueue(int k) {
maxSize = k;
circularQueue = new int[maxSize];
front = 0;
rear = -1;
curSize = 0;
}
public boolean enQueue(int value) {
if(!isFull()){
rear += 1;
rear %= maxSize;
circularQueue[rear] = value;
curSize++;
return true;
}else{
return false;
}
}
public boolean deQueue() {
if(!isEmpty()){
front += 1;
front %= maxSize;
curSize--;
return true;
}else{
return false;
}
}
public int Front() {
return isEmpty()? -1: circularQueue[front];
}
public int Rear() {
return isEmpty()? -1: circularQueue[rear];
}
public boolean isEmpty() {
return curSize == 0;
}
public boolean isFull() {
return curSize == maxSize;
}
}
/**
* Your MyCircularQueue object will be instantiated and called as such:
* MyCircularQueue obj = new MyCircularQueue(k);
* boolean param_1 = obj.enQueue(value);
* boolean param_2 = obj.deQueue();
* int param_3 = obj.Front();
* int param_4 = obj.Rear();
* boolean param_5 = obj.isEmpty();
* boolean param_6 = obj.isFull();
*/