Python链接列表优先级队列



我正在尝试使用链接列表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()

在代码的这一部分中

                if (pri > curr.get_priority()):     
                    self._head = node

您没有分配下一个元素,而是分配了新的头,而忘记了其他所有内容。应该是:

                if (pri > curr.get_priority()):     
                    previous_element.set_next(node)
                    node.set_next(curr)

最新更新