LeedCode 之 Merge Two Sorted Lists

本文介绍了一种合并两个已排序链表的方法,通过迭代或递归方式实现,保持合并后链表的排序特性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接:Merge Two Sorted Lists
仔细读题目并理解题意!!!!!!!
这道题是要Merge two sorted linked lists,重点是sorted,将已经排好序的列表合并,那么合并后的列表自然也是排好序的。
刚开始没注意到排序问题,一直不知道问题出现在哪里,后来发现是这么弱智的问题,简直有毒啊啊啊啊啊
思路:通过比较l1和l2值得大小,将小的值加入到l3,并且指向next;当一个列表指向null时,那么直接将另一个列表的剩余部分加入到l3
代码:

public class Solution {
      public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l2==null)
            return l1;
        if(l1==null)
            return l2;
        ListNode head = new ListNode(-1);
        ListNode l3 = head;
        while(l1!=null&&l2!=null){
            if(l1.val<l2.val){
                l3.next = new ListNode(l1.val);
                l3 = l3.next;
                l1 = l1.next;
            }
            else {
                l3.next = new ListNode(l2.val);
                l3 = l3.next;
                l2 = l2.next;
            }
        }    
            if(l1==null)
                l3.next = l2;
            else
                l3.next = l1;
        return head.next;
    }
}

同样在网上看到了有人使用递归的方式实现。

public class Solution {
     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        if(l2==null)
            return l1;
        if(l1==null)
            return l2;
        ListNode l3;

            if(l1.val<l2.val){
                l3 = l1;
                l3.next = mergeTwoLists(l1.next,l2);
            }
            else {
                l3 = l2;
                l3.next = mergeTwoLists(l1,l2.next);
            }
        return l3;
    }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值