试解leetcode算法题--设计循环队列

本文详细介绍了一种基于链表实现的循环队列数据结构,包括队列的基本操作如插入、删除、获取队首和队尾元素等。通过具体代码示例,展示了如何判断队列的空满状态,并提供了完整的实现细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<题目描述>
设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 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;
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值