Python中链表的合并K个有序链表操作

2023-04-11 00:00:00 合并 有序 链表

要合并k个已排序的链表,可以使用分治的方法。首先将k个链表分为两组,然后递归地将每组中的链表合并,最后将两个已合并的链表合并成一个链表即可。

下面是Python中链表合并K个有序链表的代码演示:

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

def mergeKLists(lists):
    if not lists:
        return None
    if len(lists) == 1:
        return lists[0]
    mid = len(lists) // 2
    left = mergeKLists(lists[:mid])
    right = mergeKLists(lists[mid:])
    return merge(left, right)

def merge(l1, l2):
    dummy = ListNode(0)
    curr = dummy
    while l1 and l2:
        if l1.val < l2.val:
            curr.next = l1
            l1 = l1.next
        else:
            curr.next = l2
            l2 = l2.next
        curr = curr.next
    if l1:
        curr.next = l1
    if l2:
        curr.next = l2
    return dummy.next

# 测试代码
l1 = ListNode(1)
l1.next = ListNode(4)
l1.next.next = ListNode(5)

l2 = ListNode(1)
l2.next = ListNode(3)
l2.next.next = ListNode(4)

l3 = ListNode(2)
l3.next = ListNode(6)

lists = [l1, l2, l3]

merged_list = mergeKLists(lists)

while merged_list:
    print(merged_list.val, end=" ")
    merged_list = merged_list.next
# 输出:1 1 2 3 4 4 5 6

以上代码将三个有序链表合并成一个有序链表,并将结果打印出来。如果需要测试其他的范例,可以将节点的值修改为字符串类型的“pidancode.com”、“皮蛋编程”等。

相关文章