Python3 实现简单循环队列

本文详细介绍了一种基于FIFO原则的循环队列数据结构设计与实现,通过具体代码示例,展示了如何利用循环队列的优势,即重复利用已使用的空间,解决普通队列在空间管理上的局限性。

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

题目来自Leetcode 队列

设计你的循环队列实现。 循环队列是一种线性数据结构,其操作表现基于 FIFO(先进先出)原则并且队尾被连接在队首之后以形成一个循环。它也被称为“环形缓冲器”。

循环队列的一个好处是我们可以利用这个队列之前用过的空间。在一个普通队列里,一旦一个队列满了,我们就不能插入下一个元素,即使在队列前面仍有空间。但是使用循环队列,我们能使用这些空间去存储新的值。

你的实现应该支持如下操作:

MyCircularQueue(k): 构造器,设置队列长度为 k 。
Front: 从队首获取元素。如果队列为空,返回 -1 。
Rear: 获取队尾元素。如果队列为空,返回 -1 。
enQueue(value): 向循环队列插入一个元素。如果成功插入则返回真。
deQueue(): 从循环队列中删除一个元素。如果成功删除则返回真。
isEmpty(): 检查循环队列是否为空。
isFull(): 检查循环队列是否已满。
 

我的解:

class MyCircularQueue:

	def __init__(self, k: int): #and
		"""
		Initialize your data structure here. Set the size of the queue to be k.
		"""
		self.__length = k
		self.queue = [0] * k
		self.__head = 0
		self.__tail = -1
		self.__count = 0

	def enQueue(self, value: int) -> bool:
		"""
		Insert an element into the circular queue. Return true if the operation is successful.
		"""
		if self.isFull() == False:
			if self.__tail == self.__length-1: #尾指到最后一个空间了
				self.__tail = 0
			else:
				self.__tail += 1
			self.queue[self.__tail] = value
			self.__count += 1
			return True
		else:
			return False


	def deQueue(self) -> bool:
		"""
		Delete an element from the circular queue. Return true if the operation is successful.
		"""
		if self.isEmpty() == False :
			self.queue[self.__head] = 0
			self.__count -= 1
			if self.__head != self.__tail:
				if self.__head == self.__length-1:
					self.__head = 0
				else:
					self.__head += 1
			else:
				self.__head = 0
				self.__tail = -1
			return True
		else:
			return False

	def Front(self) -> int:
		"""
		Get the front item from the queue.
		"""
		if self.isEmpty():
			return -1
		else:
			return self.queue[self.__head]

	def Rear(self) -> int:
		"""
		Get the last item from the queue.
		"""
		if self.isEmpty():
			return -1
		else:
			return self.queue[self.__tail]

	def isEmpty(self) -> bool:
		"""
		Checks whether the circular queue is empty or not.
		"""
		if self.__count == 0:
			return True 
		else:
			return False

	def isFull(self) -> bool:
		"""
		Checks whether the circular queue is full or not.
		"""
		if self.__count == self.__length:
			return True
		else:
			return False
		
### 基于 `collections.deque` 的循环队列实现 以下是使用 Python 中的 `collections.deque` 来实现一个简单循环队列的方法。通过设置 `maxlen` 参数,可以控制队列的最大长度。当队列达到其最大容量并尝试添加新的元素时,最旧的元素会被自动移除。 #### 循环队列类定义 下面是一个基于 `deque` 的循环队列实现: ```python from collections import deque class CircularQueue: def __init__(self, capacity): self.queue = deque(maxlen=capacity) def enqueue(self, item): """向队列尾部添加元素""" self.queue.append(item) def dequeue(self): """从队列头部删除元素""" if not self.is_empty(): return self.queue.popleft() raise IndexError("dequeue from an empty queue") def is_full(self): """判断队列是否已满""" return len(self.queue) == self.queue.maxlen def is_empty(self): """判断队列是否为空""" return len(self.queue) == 0 def size(self): """返回当前队列大小""" return len(self.queue) def front(self): """查看队首元素""" if not self.is_empty(): return self.queue[0] raise IndexError("front from an empty queue") def rear(self): """查看队尾元素""" if not self.is_empty(): return self.queue[-1] raise IndexError("rear from an empty queue") ``` #### 示例用法 以下是如何使用上述 `CircularQueue` 类的一个例子: ```python cq = CircularQueue(capacity=3) # 创建一个容量为3循环队列 print(cq.is_empty()) # 输出 True,因为队列初始为空 cq.enqueue(1) cq.enqueue(2) cq.enqueue(3) print(cq.size()) # 输出 3,表示当前队列中有三个元素 print(cq.is_full()) # 输出 True,因为队列已经达到最大容量 cq.enqueue(4) # 当再次添加元素时,最早进入队列的元素被移除 print(cq.rear()) # 输出 4,最新入队的元素是4 print(cq.front()) # 输出 2,最早的元素现在变成了2 item = cq.dequeue() # 移除队首元素 print(item) # 输出 2,移除了最早的元素 print(cq.front()) # 输出 3,现在的队首元素变成3 print(cq.size()) # 输出 2,剩余两个元素在队列中 ``` 以上代码展示了如何利用 `deque` 构建一个具有固定容量的循环队列,并提供了基本的操作功能,如入队、出队以及状态查询等功能[^1]。 ### 关键特性说明 - **`maxlen` 参数的作用**:`deque` 支持通过 `maxlen` 参数设定固定的长度。一旦超出该长度,左侧的老数据会自动被丢弃以腾出空间给新数据[^5]。 - **线程安全问题**:需要注意的是,虽然 `deque` 提供了一些高效的 FIFO/LIFO 操作支持,但它本身并不是线程安全的数据结构。如果需要在线程环境中使用,则需额外引入锁机制或其他同步工具[^4]。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值