牛客刷题——合并两个排序的链表

描述(注:合并两个排序的链表_牛客题霸_牛客网

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

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

如输入{1,3,5},{2,4,6}时,合并后的链表为{1,2,3,4,5,6},所以对应的输出为{1,2,3,4,5,6},转换过程如下图所示:

链表的组成:节点(数值+下一个数值的地址)

该题可以一个个数值拿出来比一比,小的放入,大的留下。下面分别给出Python和JAVA的代码。

class Solution:
    def Merge(self , pHead1: ListNode, pHead2: ListNode) -> ListNode:
        pre=ListNode(-1)
        cur=pre
        while(pHead1 and pHead2):
            if(pHead1.val<=pHead2.val):
                cur.next=pHead1
                cur=cur.next
                pHead1=pHead1.next
            else:
                cur.next=pHead2
                cur=cur.next
                pHead2=pHead2.next

        if(pHead1):
            cur.next=pHead1
        else:
            cur.next=pHead2
        return pre.next

这段代码,定义的两个指针(cur和pre)

每次比较pHead1和pHead2的值后,就将cur指向较小的那个值(cur.next=pHead1(pHead2)),并赋值给原本的cur。同时比较玩的链表,指向下一个数(pHead1=pHead1.next)。

 public ListNode Merge(ListNode pHead1,ListNode pHead2){
         if(pHead1==null){
            return pHead2;
         }if(pHead2==null){
            return pHead1;
         }
         ListNode cur=null;
         ListNode pre=null;
         while(pHead1!=null && pHead2!=null){

            if(pHead1.val<=pHead2.val){
                if(cur==null){
                    cur=pre=pHead1;
                }
                else{
                    pre.next=pHead1;
                    pre=pre.next; 
                }
                pHead1=pHead1.next;
            }else{
                if(cur==null){
                    cur=pre=pHead2;
                }else{
                    pre.next=pHead2;
                    pre=pre.next;
                }
                pHead2=pHead2.next;
            }
         }
         if(pHead1==null){
            pre.next=pHead2;
         }
         else{
            pre.next=pHead1;
         }
         return cur;
      }

方法概述

  • 核心思想:通过改变节点的指针方向,将两个链表合并为一个递增链表,而不创建新节点(即原地合并)。

  • 使用哑节点(dummy node):创建一个哑节点作为新链表的起始点,这样可以简化边界处理(如头节点的选择)。

  • 双指针遍历:使用两个指针分别遍历两个链表,比较当前节点的值,将较小值的节点链接到新链表中。

  • 处理剩余节点:当其中一个链表遍历完后,直接将另一个链表的剩余部分链接到新链表的末尾。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值