首页 > 解决方案 > 将链表节点放入 Python 优先级队列的问题

问题描述

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

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

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

链表类:

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

标签: pythonlinked-listpriority-queue

解决方案


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

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

推荐阅读