我正在尝试在python中实现循环队列,而我当前的程序一直在给我错误,我想知道问题并解决。
我当前的程序是:
# circular queue
class circularQueue:
def __init__(self, maxsize):
self.front = 0
self.rear = -1
self.queue = []
self.size = 0 # elements in the queue
self.maxsize = maxsize #size of the array(queue)
def isEmpty(self):
if self.size == 0:
return True
else:
return False
def isFull(self):
if self.size == self.maxsize:
return True
else:
return False
def enQueue(self, newItem):
if self.size == self.maxsize:
print('Queue Full')
else:
self.rear = (self.rear + 1) % self.maxsize # mod = remainder
self.queue[self.rear] = newItem
self.size += self.size
def deQueue(self):
if self.size == 0:
print('Queue Empty')
item = null
else:
item = self.queue[self.front]
self.front = (self.front + 1) % self.maxsize
self.size = self.size - 1
return item
如果我尝试操作
q = circularQueue(6)
q.enQueue('k')
它说
self.queue[self.rear] = newItem
IndexError: list assignment index out of range
请帮我 ......
最佳答案
您正在尝试填写一个不存在的列表元素。相反,在扩展现有列表时,必须使用append
:
self.queue.append(newItem)
另外,我不希望每次执行此操作时都希望将self.size加倍-查看下一行:
self.size += self.size
尝试
self.size += 1