Error: Merge two sorted linkedlist using dummy head technique in Python

Error: Merge two sorted linkedlist using dummy head technique in Python

我正在尝试使用虚拟头技术解决合并两个已排序链表的问题。出于某种原因,我在将参数传递给我的假头支架时出错。输出假设像这样合并两个链表:1-> 1-> 2-> 3-> 7-> None

如果您能指导我的虚拟头变量中需要传递哪些数据,我将很高兴?提前致谢!这是我的错误:

    dummy = LinkedList()
TypeError: __init__() missing 1 required positional argument: 'data

这是我的完整代码:


class LinkedList:
    def __init__(self, data):
        self.data = data
        self.next = None


def print_list(head: LinkedList) -> None:
    while head:
        print(head.data, end=" -> ")
        head = head.next
    print("None")


def merge_lists(headA, headB):
    dummy = LinkedList()
    curr = dummy

    while headA != None and headB != None:
        if headA.data < headB.data:
            curr.next = headA
            headA = headA.next
        else:
            curr.next = headB
            headB = headB.next

        curr = curr.next

    if headA != None:
        curr.next = headA
    else:
        curr.next = headB

    return dummy.next



node1 = LinkedList(1)
node1.next = LinkedList(2)
node1.next.next = LinkedList(7)


node2 = LinkedList(1)
node2.next = LinkedList(3)

print(merge_lists(node1, node2)) # 1-> 1-> 2-> 3-> 7-> None

因为它是一个虚拟节点,你永远不会使用那个节点的数据属性,你可以传递任何东西作为参数,比如None:

dummy = LinkedList(None)

或者,您可以指定提供参数是可选的,并按如下方式定义构造函数:

class LinkedList:
    def __init__(self, data=None):
        self.data = data
        self.next = None

不相关,但在您的脚本末尾您有:

print(merge_lists(node1, node2))

这将打印对象引用。您可能想调用为此目的定义的函数:

print_list(merge_lists(node1, node2))

如果你想让 print 像那样工作,那么不用 print_list 函数,用 __iter__ 方法丰富 LinkedList 来简化对值的迭代列表,以及 __repr____str__ 方法,如下所示:

class LinkedList:
    def __init__(self, data=None):
        self.data = data
        self.next = None

    def __iter__(self):
        head = self
        while head:
            yield head.data
            head = head.next
        yield None  # Optional

    def __repr__(self):
        return " -> ".join(map(str, self))

...然后你可以做

print(merge_lists(node1, node2))