LeetCode:21. Merge Two Sorted Lists

博客围绕LeetCode 21题合并两个有序链表展开。思路是同时遍历两个链表,将val值小的节点插入新链表,一个链表遍历完后,把另一个剩余链表合并到新链表,还给出了Python代码实现。

LeetCode:21. Merge Two Sorted Lists

Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

Example:

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

合并两个有序链表

思路

同时遍历两个链表,val值小的插入到新的链表,知道有个链表遍历结束,再把剩余的那个链表合并到新链表。

Python 代码实现

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
        head1,head2 = l1,l2
        newl = ListNode(0)
        newhead = newl
        while (head1 is not None and head2 is not None):
            if head1.val <= head2.val:
                tmp = ListNode(head1.val)
                newhead.next = tmp
                newhead = newhead.next
                head1 = head1.next
            elif head2.val <= head1.val:
                tmp = ListNode(head2.val)
                newhead.next = tmp
                newhead = newhead.next
                head2 = head2.next
                
        if head1 is not None:
            newhead.next = head1
                
        if head2 is not None:
            newhead.next = head2
        
        return newl.next

THE END.

合并两个有序链表的递归实现是一种直观且优雅的方法。该方法利用递归调用来逐步解决子问题,最终构建出完整的解决方案。以下是具体的实现步骤和原理: ### 递归实现原理 1. **递归边界条件**:如果其中一个链表为空,则直接返回另一个链表作为合并后的结果。 2. **递归调用**:比较两个链表当前节点的值,选择较小的节点作为新链表的当前节点,并递归地合并剩余部分。 ### 代码示例 ```python # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]: # 递归边界条件:如果其中一个链表为空,直接返回另一个链表 if not list1: return list2 if not list2: 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 ``` ### 详细解析 1. **递归边界条件**: - 如果 `list1` 为空,则返回 `list2`。这是因为 `list2` 中的所有节点都已经按升序排列,可以直接接在结果链表后面。 - 如果 `list2` 为空,则返回 `list1`。理由同上,`list1` 的所有节点可以直接接在结果链表后面 [^3]。 2. **递归调用**: - 比较 `list1` 和 `list2` 当前节点的值,选择较小的节点作为当前节点。 - 如果 `list1.val` 小于或等于 `list2.val`,则递归调用 `mergeTwoLists` 函数,传入 `list1.next` 和 `list2`,并将返回的结果赋值给 `list1.next`,然后返回 `list1`。 - 否则,递归调用 `mergeTwoLists` 函数,传入 `list1` 和 `list2.next`,并将返回的结果赋值给 `list2.next`,然后返回 `list2` [^4]。 ### 示例 假设我们有两个链表: - `list1`: 1 -> 3 -> 5 - `list2`: 2 -> 4 -> 6 递归调用过程如下: 1. 比较 `list1.val` (1) 和 `list2.val` (2),选择 `list1` 的节点 1。 2. 递归调用 `mergeTwoLists(list1.next, list2)`,即 `mergeTwoLists(3 -> 5, 2 -> 4 -> 6)`。 3. 比较 `3` 和 `2`,选择 `list2` 的节点 2。 4. 递归调用 `mergeTwoLists(list1, list2.next)`,即 `mergeTwoLists(3 -> 5, 4 -> 6)`。 5. 继续这个过程,直到其中一个链表为空。 最终结果链表为:1 -> 2 -> 3 -> 4 -> 5 -> 6。 ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值