循环队列 Python
我正在尝试在Python中创建一个循环队列,这样当数组的最后一个元素被访问时,它会指向队列的开头。我正在处理入队(enqueue)的方法,但遇到了一些问题。我想要一个大小为4的数组,可以将值放入到第4个位置,但当执行到elif语句时,我收到了这个错误。
错误信息是:TypeError: unsupported operand type(s) for +: 'Node' and 'int'(类型错误:不支持的操作数类型:'Node'和'int')
有什么想法吗?
class Node(object):
def __init__(self, item = None):
self.item = [None] * 4
self.next = None
self.previous = None
class CircularQueue(object):
def __init__(self):
self.length = 0
self.head = None
self.tail = None
def enqueue(self, x):
newNode = Node(x)
newNode.next = None
if self.head == None:
self.head = newNode
self.tail = newNode
elif self.length < 4:
self.tail.next = newNode
newNode.previous = self.tail
self.tail = newNode
else:
self.tail = (self.tail + 1) % 4
self.length += 1
def dequeue(self):
if self.count == 0:
print ("The Queue is empty!")
self.count -= 1
return self.item.pop()
def size(self):
return self.length
4 个回答
1
如果你只是想让尾巴到达头部,比如说:
list = [1,2,3]
list = list + list[0:1]
你会得到:
[1,2,3,1]
也许这就是最简单的方法。
1
我会尽量给你一些方向,因为看起来你正在尝试学习如何实现一个循环队列,同时可能也在学习编程。错误信息在告诉你,变量 self.tail 是一个对象,不能和数字(整数)相加。
出问题的代码行是:
self.tail = (self.tail + 1) % 4
这行代码导致了错误。不过在尝试修复这一行之前,有一些基本概念需要理解。例如,你不需要在你的 Node 对象里创建一个数组。self.item 可以设置成任何东西,这样可能会让你对循环队列的目的感到困惑。例如,代替
self.item = [None] * 4
你可以使用
self.item = item
然后当你创建 Node 对象时,可以用类似下面的方式:
mycircularqueue = CircularQueue()
mycircularqueue.enqueue('cat')
mycircularqueue.enqueue('dog')
mycircularqueue.enqueue('mouse')
来向你的队列添加三个项目。
1
你的问题出在这里:
self.tail + 1
但是在这之前,你把尾部(tail)设置成了一个节点(Node):
self.tail = newNode
所以就出现了这个错误。
19
如果你不需要自己去实现这个功能,可以直接使用标准库里的 deque
。
from collections import deque
circular_queue = deque([1,2], maxlen=4)
circular_queue.append(3)
circular_queue.extend([4])
# at this point you have [1,2,3,4]
print(circular_queue.pop()) # [1,2,3] --> 4
# key step. effectively rotate the pointer
circular_queue.rotate(-1) # negative to the left. positive to the right
# at this point you have [2,3,1]
print(circular_queue.pop()) # [2,3] --> 1