gpt4 book ai didi

python - 循环队列 Python

转载 作者:太空宇宙 更新时间:2023-11-04 06:47:24 25 4
gpt4 key购买 nike

我正在尝试在 Python 中创建一个循环队列,以便在到达数组中的最后一个元素时指向回头。我正在研究入队方法,但遇到了一些问题。我正在尝试拥有一个大小为 4 的数组,并且我能够将值排到第 4 个位置,但是当它执行 elif 语句时,我收到此错误。

TypeError:+ 不支持的操作数类型:'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

最佳答案

如果你不必自己实现这个,你可以使用标准库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 - 循环队列 Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22772764/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com