首页 > 试题广场 >

链表合并

[编程题]链表合并
  • 热度指数:3742 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 32M,其他语言64M
  • 算法知识视频讲解
请编写一段代码,实现两个单向有序链表的合并

输入描述:
第一行一个链表,如1 2 3 4 5

第二行一个链表,如2 3 4 5 6


输出描述:
输出:1 2 2 3 3 4 4 5 5 6
示例1

输入

1 2 3 4 5
2 3 4 5 6

输出

1 2 2 3 3 4 4 5 5 6
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

class Solution:
    def mergeTwoLists(self, list1, list2):
        if list1 is None:
            return list2
        if list2 is None:
            return list1
        if list1.val < list2.val:
            list1.next = self.mergeTwoLists(list1.next, list2)
            return list1
        else:
            list2.next = self.mergeTwoLists(list1, list2.next)
            return list2

def list_to_linkedlist(lst):
    dummy = ListNode(0)
    current = dummy
    for val in lst:
        current.next = ListNode(val)
        current = current.next
    return dummy.next

def linkedlist_to_list(head):
    result = []
    current = head
    while current:
        result.append(current.val)
        current = current.next
    return result

if __name__ == "__main__":
    list1 = list(map(int, input().split()))
    list2 = list(map(int, input().split()))

    # 将输入的列表转换为链表
    head1 = list_to_linkedlist(list1)
    head2 = list_to_linkedlist(list2)

    solution = Solution()
    merged_head = solution.mergeTwoLists(head1, head2)

    # 将合并后的链表转换为列表并输出
    merged_list = linkedlist_to_list(merged_head)
    print(" ".join(map(str, merged_list)))

发表于 2025-05-25 14:51:22 回复(0)