我一直在努力用python中的链表结构实现优先级队列。我已经取消了insert方法和remove方法,但是,我们必须编写称为split_alt
的方法时遇到了问题。
队列定义为:
class _PQ_Node:
def __init__(self, value, _next):
"""
-------------------------------------------------------
Initializes a priority queue node that contains a copy of value
and a link to the next node in the priority queue
Use: node = _PQ_Node(value, _next)
-------------------------------------------------------
Parameters:
value - value value for node (?)
_next - another priority queue node (_PQ_Node)
Returns:
a new Priority_Queue object (_PQ_Node)
-------------------------------------------------------
"""
self._value = deepcopy(value)
self._next = _next
Priority_Queue类:
def __init__(self):
"""
-------------------------------------------------------
Initializes an empty priority queue.
Use: pq = Priority_Queue()
-------------------------------------------------------
Returns:
a new Priority_Queue object (Priority_Queue)
-------------------------------------------------------
"""
self._front = None
self._rear = None
self._count = 0
我们不允许更新传递给方法的任何参数,也不得编写新方法。
到目前为止,我对split_alt的了解是:
def split_alt(self):
"""
-------------------------------------------------------
Splits a priority queue into two with values going to alternating
priority queues. The source priority queue is empty when the method
ends. The order of the values in source is preserved.
Use: target1, target2 = source.split_alt()
-------------------------------------------------------
Returns:
target1 - a priority queue that contains alternating values
from the current queue (Priority_Queue)
target2 - priority queue that contains alternating values
from the current queue (Priority_Queue)
-------------------------------------------------------
"""
target1 = Priority_Queue()
target2 = Priority_Queue()
c = 0
current = self._front
while current:
if c % 2 == 0:
if not target1._front:
target1._front = current
target1._rear = current
t1 = target1._front
target1._count += 1
else:
t1._next = current
target1._rear = current
target1._count += 1
t1 = t1._next
else:
if not target2._front:
target2._front = current
target2._rear = current
t2 = target2._front
target2._count += 1
else:
t2._next = current
target2._rear = current
target2._count += 1
t2 = t2._next
self._front = current._next
current = self._front
c += 1
self._count -= 1
self._front = None
self._rear = None
return target1,target2
最低值具有最高优先级。
运行此命令时,由于某种原因,它总是将最后一个值也插入到我的target1列表中。我不知道为什么。 例如,使用优先级队列列表(例如[11,22,33,44,55,66])进行测试可以得出:
Target1值: 11 33 55 66
Target2值: 22 44 66
来源:
同样,我不确定为什么也将66添加到target1。
有人能对此有所启发吗?
非常感谢。