我正在尝试使用链表ADT创建优先级队列, 但我遇到队列的插入功能有问题。 队列需要从较大的正值排序到较低的值。 只要添加了具有更高优先级的对象,就会删除低于新添加的现有对象。
class WackyNode():
'''represents a WackyNode as a building block of a single linked list'''
def __init__(self: 'WackyNode',
item: object, priority: int, next_node=None) -> None:
self._next = next_node
self._item = item
self._priority = priority
def set_next(self, next_node):
'''(Node, Node) -> NoneType
set node to point to next_node'''
self._next = next_node
def set_item(self, item):
'''(Node, obj) ->NoneType
set the _item to a new value'''
self._item = item
def get_next(self):
'''(Node) -> Node
returns the reference to next node'''
return self._next
def get_item(self):
'''(Node) -> obj
returns the item of this node'''
return self._item
def get_priority(self: 'WackyNode') -> int:
return self._priority
def set_priority(self: 'WackyNode', priority: int) -> None:
self._priority = priority
def __str__(self):
'''(Node) -> str
returns the item of this node and the reference to next node'''
return "(" + str(self._item) + ", " + str(hex(id(self._next))) + ")"
class SingleLinkedList():
''' represents a single linked list'''
def __init__(self):
'''(SingleLinkedList) ->NoneType
initializes the references of an empty SLL'''
self._size = 0
self._head = None
self._tail = None
def insert(self, item, pri):
'''(SingleLinkedList, obj) -> NoneType
adds a node to the first of the SLL'''
# create a node that point to the head
node = WackyNode(item, pri, self._head)
# let head point to the node
if (self._head == None):
self._head = node
else:
curr = self._head
prev = curr
if (self._size >= 1):
while curr is not None:
if (pri > curr.get_priority()):
self._head = node
elif (pri < curr.get_priority()):
point = curr.get_next()
node = WackyNode(item, pri, self._head)
prev.set_next(node)
node.set_next(point)
curr = curr.get_next()
答案 0 :(得分:0)
在这段代码中
if (pri > curr.get_priority()):
self._head = node
你没有分配下一个元素,你分配新头并忘记其他一切。应该是:
if (pri > curr.get_priority()):
previous_element.set_next(node)
node.set_next(curr)