class MyCircularQueue {
vector<int> data;
int head, tail;
int size;
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k) {
data.resize(k); //通过resize重新分配资源空间
head = -1;
tail = -1;
size = k;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value) {
if(isFull())
return false;
if(isEmpty())
head = 0; //首次入队,更新队列首位,离开初始化状态
//通过取余可以确定在队列中的任何位置
tail = (tail + 1) % size;
data[tail] = value;
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() {
if(isEmpty())
return false;
//出队列后,队列为空,初始化队列首尾到默认值
if(head == tail) {
head = tail = -1;
return true;
}
head = (head + 1) % size;
return true;
}
/** Get the front item from the queue. */
int Front() {
if(isEmpty())
return -1;
return data[head];
}
/** Get the last item from the queue. */
int Rear() {
if(isEmpty())
return -1;
return data[tail];
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty() {
//认为初始化状态为空,为空后也会重置为初始化状态
return head == -1;
}
/** Checks whether the circular queue is full or not. */
bool isFull() {
return (tail + 1) % size == head;
}
};
循环队列--CircularQueue
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...