【问题标题】:Problem in putting Linked List node into the Python Priority Queue将链表节点放入 Python 优先级队列时出现问题
【发布时间】:2021-05-07 15:08:14
【问题描述】:

我基本上是在尝试将链接列表节点放入优先级队列中。这里 ListNode 是我的 LinkedList 类,lists 是一个包含不同链表头的 python 列表。我不知道为什么会收到以下错误消息。

TypeError:“ListNode”和“ListNode”实例之间不支持“

  Q = PriorityQueue()
for node in lists:
    if node:
        Q.put((node.val,node))

LinkedList 类:

class ListNode:
def __init__(self, val=0, next=None):
    self.val = val
    self.next = next

【问题讨论】:

    标签: python linked-list priority-queue


    【解决方案1】:

    哦,我终于明白了。实际上是因为相同的优先级。只要有两个具有相同优先级的值,优先级队列就会尝试比较 ListNode 对象并引发此错误。一个简单的解决方案是使用 counter 变量。

    Q = PriorityQueue()
    count = 0
    for node in lists:
       if node:
           Q.put((node.val, count, node))
           count += 1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多