代码练习3-实现两个链表递增排序

输入两个递增的链表,单个链表的长度为n,合并这两个链表并使新链表中的节点仍然是递增排序的。

数据范围: 0≤𝑛≤1000,−1000≤节点值≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)

示例转换:

C++核心代码实现 

public class Solution {
    public ListNode Merge(ListNode head1, ListNode head2) {
        ListNode dummy = new ListNode(-1);  // 创建虚拟头节点,值为 -1(值无所谓,只是个占位)
        ListNode current = dummy;  // current 初始指向 dummy 节点

        while (head1 != null && head2 != null) {  // 当两个链表都不为空时
            if (head1.val <= head2.val) {  // 比较 head1 和 head2 的值
                current.next = head1;  // 将较小的 head1 节点连接到 current 后面
                head1 = head1.next;  // 移动 head1 指针
            } else {
                current.next = head2;  // 将较小的 head2 节点连接到 current 后面
                head2 = head2.next;  // 移动 head2 指针
            }
            current = current.next;  // 移动 current 指针
        }

        // 处理剩余的节点
        if (head1 != null) {
            current.next = head1;  // 如果 head1 不为空,将其全部连接到 current 后面
        }
        if (head2 != null) {
            current.next = head2;  // 如果 head2 不为空,将其全部连接到 current 后面
        }

        return dummy.next;  // 返回合并后的链表的头节点,跳过虚拟头节点 dummy
    }
}

Python核心代码实现

class Solution:
    def Merge(self, pHead1: ListNode, pHead2: ListNode) -> ListNode:
        # 创建一个虚拟头节点
        dummy = ListNode(0)
        current = dummy

        # 逐个比较两个链表的节点值,选择较小的节点连接到新链表
        while pHead1 and pHead2:
            if pHead1.val <= pHead2.val:
                current.next = pHead1
                pHead1 = pHead1.next
            else:
                current.next = pHead2
                pHead2 = pHead2.next
            current = current.next

        # 将剩余的节点连接到新链表
        if pHead1:
            current.next = pHead1
        if pHead2:
            current.next = pHead2

        # 返回合并后的链表头节点(跳过虚拟头节点)
        return dummy.next

  • 22
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值