我正在尝试实现基于圆形数组的队列的insert方法,但是无法更新队列的后面。这是我的代码:
frame: .zero
有什么建议吗?
编辑: 这是删除实现:
def __init__(self, max_size):
"""
-------------------------------------------------------
Initializes an empty queue. Data is stored in a fixed-size list.
Use: cq = Queue(max_size)
-------------------------------------------------------
Parameters:
max_size - maximum size of the queue (int > 0)
Returns:
a new Queue object (Queue)
-------------------------------------------------------
"""
assert max_size > 0, "Queue size must be > 0"
self._max_size = max_size
self._values = [None] * self._max_size
self._front = 0
self._rear = 0
self._count = 0
def insert(self, value):
'''-------------------------------------------------------
Adds a copy of value to the rear of the queue.
Use: cq.insert( value )
-------------------------------------------------------
Parameters:
value - a data element (?)
Returns:
None
-------------------------------------------------------'''
assert (self._count < self._max_size), 'queue is full'
self._values.append(deepcopy(value))
self._count += 1
self._rear = (self._rear - 1) % self._count
return
答案 0 :(得分:1)
通过追加添加项目时,您的列表将扩展到超出预先分配的最大长度。然后,您将更新self._rear
,就好像您要将其用作插入索引一样,但实际上从未将其用于任何东西。我已经实现了您的代码,仅对变量名进行了很小的改动(为了对我更有意义),并按照我认为您打算的方式利用了self._rear (now: self._write_cursor)
。
class CQ: #Circular Queue
def __init__(self, maxsize):
self._maxsize = maxsize
self._write_cursor = 0
self._read_cursor = 0
self._len = 0
self._values = [None] * maxsize
def insert(self, item):
if self._len < self._maxsize:
self._values[self._write_cursor] = item
self._write_cursor = (self._write_cursor + 1) % self._maxsize
self._len = self._len + 1
else:
raise IndexError('can\'t push to full queue')
def remove(self):
if self._len > 0:
out = self._values[self._read_cursor]
self._read_cursor = (self._read_cursor + 1) % self._maxsize
self._len -= 1
return out
else:
raise IndexError('can\'t pop from empty queue')