循环队列Python [英] Circular Queue Python
本文介绍了循环队列Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
TypeError:不支持的+:'Node'和'int'的操作数类型
任何想法?
code> 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 =无
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
其他:
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
解决方案
如果您不需要自己实现,可以使用标准库 deque
from collections import deque
circular_queue = deque([1,2],maxlen = 4)
circular_queue.append(3)
circular_queue.extend([4])
#在这一点上你有[1 ,2,3,4]
print(circular_queue.pop())#[1,2,3] - > 4
#关键步骤。有效地向左旋转指针
circular_queue.rotate(-1)#negative。对于正确的
#在这一点上你有[2,3,1]
print(circular_queue.pop())#[2,3] - > 1
I am trying to make a circular queue in Python so that when the last element in the array is reached to points back to the head. I am working on the enqueue method and I am having some issues. I am trying to have an array of size 4 and I am able to enqueue values up to the 4th spot, but when it executes the elif statement I receive this error.
TypeError: unsupported operand type(s) for +: 'Node' and 'int'
Any thoughts?
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
解决方案
If you don't have to implement this yourself, you can use the standard library 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
这篇关于循环队列Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文