<题目描述>
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。
<原题链接>
https://leetcode-cn.com/problems/design-circular-queue/
<理明思路>
可以使用链表来实现环形队列。
<样例代码>
#include<iostream>
using namespace std;
class MyCircularQueue {
public:
/** Initialize your data structure here. Set the size of the queue to be k. */
MyCircularQueue(int k)
{
deque_size = k;
p = NULL;
tail = NULL;
head = NULL;
}
/** Insert an element into the circular queue. Return true if the operation is successful. */
bool enQueue(int value)
{
if (isFull())
return false;
p = new Deque;
p->x = value;
p->next = NULL;
if (isEmpty())
{
head = p;
tail = p;
head->next = tail;
tail->next = head;
}
else
{
tail->next = p;
p->next = head;
tail = p;
}
return true;
}
/** Delete an element from the circular queue. Return true if the operation is successful. */
bool deQueue() //删掉头部元素
{
if (isEmpty())
return false;
Deque * temp;
if (head == tail)
{
delete tail;
head = NULL;
tail = NULL;
p = NULL;
}
else
{
tail->next = head->next;
delete head;
head = tail->next;
}
return true;
}
/** Get the front item from the queue. */
int Front()
{
if (isEmpty())
return -1;
return head->x;
}
/** Get the last item from the queue. */
int Rear()
{
if (isEmpty())
return -1;
return tail->x;
}
/** Checks whether the circular queue is empty or not. */
bool isEmpty()
{
if (head == NULL)
return true;
else
return false;
}
/** Checks whether the circular queue is full or not. */
bool isFull()
{
Deque * temp;
int _count = 0;
for (temp = head; temp != tail; temp = temp->next)
_count++;
return ++_count == deque_size;
}
private:
unsigned int deque_size;
struct Deque
{
int x;
Deque * next;
}*p, *tail, *head;
};