合并两个已排序链表的返回头

2024-09-28 05:27:58 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个python函数,用于合并两个已排序的链表。我知道在python中,变量名是指向对象的引用/指针。谁能向我解释一下:

“尾巴”指向头3。在代码中,“tail”不断变化,head3似乎没有参与到操作中。head3如何自动连接到合并列表?为什么头3和“尾”相关时只改变一次

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

def merge_sorted(head1, head2):
    head3 = Node(None)
    tail = head3

    if head1 is None:
        tail.next = head2
    if head2 is None:
        tail.next = head1

    while head1 and head2:
        if head1.data <= head2.data:
            tail.next = head1
            head1 = head1.next
        else:
            tail.next = head2
            head2 = head2.next
        tail = tail.next

    return head3.next

Tags: 函数selfnonenodedataif排序is

热门问题