目录
2、循环队列(下列所有加减法都是在mod(N+1)的意义下)
3、双端循环队列(下列所有加减法都是在mod(N+1)的意义下)
1、普通队列
- 队列数组名为q[N]
- 初始化hh = 0, tt = -1, 队列的元素区间为[hh, tt]
- 入队:q[++tt] = val;
- 出队: hh++
- 队头元素: q[hh]
- 判空: hh <= tt 表示非空, hh > tt 队列为空
2、循环队列(下列所有加减法都是在mod(N+1)的意义下)
- 队列数组名q[N + 1], 循环队列最多存储N个元素,是为了区分队空和队满的情况
- 初始化hh = tt = 0, 队列的元素区间为[hh, tt),这里右侧为开区间
- 入队: q[tt++] = val
- 出队hh++;
- 队头元素:q[hh]
- 队尾元素: q[tt-1]
- 判空: hh == tt
- 队满: tt + 1 == hh
class MyCircularQueue {
public:
int hh = 0, tt = 0;
vector<int> q;
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
q.resize(k + 1);
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if (isFull()) return false;
q[tt ++ ] = value;
if (tt == q.size()) tt = 0;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if (isEmpty()) return false;
hh ++ ;
if (hh == q.size()) hh = 0;
return true;
}
/** Get the front item from the queue. */
int Front() {
if (isEmpty()) return -1;
return q[hh];
}
/** Get the last item from the queue. */
int Rear() {
if (isEmpty()) return -1;
int t = tt - 1;
if (t < 0) t += q.size();
return q[t];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
return hh == tt;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return (tt + 1) % q.size() == hh;
}
};
3、双端循环队列(下列所有加减法都是在mod(N+1)的意义下)
双端循环表示和2里面的循环队列表示是相同的,多了几个操作而已。
class MyCircularDeque {
public:
int hh = 0, tt = 0;
vector<int> q;
/** Initialize your data structure here. Set the size of the deque to be k. */
MyCircularDeque(int k) {
q.resize(k + 1);
}
int get(int x) {
return (x + q.size()) % q.size();
}
/** Adds an item at the front of Deque. Return true if the operation is successful. */
bool insertFront(int value) {
if (isFull()) return false;
hh = get(hh - 1);
q[hh] = value;
return true;
}
/** Adds an item at the rear of Deque. Return true if the operation is successful. */
bool insertLast(int value) {
if (isFull()) return false;
q[tt ++ ] = value;
tt = get(tt);
return true;
}
/** Deletes an item from the front of Deque. Return true if the operation is successful. */
bool deleteFront() {
if (isEmpty()) return false;
hh = get(hh + 1);
return true;
}
/** Deletes an item from the rear of Deque. Return true if the operation is successful. */
bool deleteLast() {
if (isEmpty()) return false;
tt = get(tt - 1);
return true;
}
/** Get the front item from the deque. */
int getFront() {
if (isEmpty()) return -1;
return q[hh];
}
/** Get the last item from the deque. */
int getRear() {
if (isEmpty()) return -1;
return q[get(tt - 1)];
}
/** Checks whether the circular deque is empty or not. */
bool isEmpty() {
return hh == tt;
}
/** Checks whether the circular deque is full or not. */
bool isFull() {
return get(hh - 1) == tt;
}
};