【LeetCode】21. Merge Two Sorted Lists

Difficulty: Easy

 More:【目录】LeetCode Java实现

Description

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

Intuition

合并两个排序的链表题目完全相同,可以采用循环和递归来实现。循环的实现代码中可以使用一个dummyHead(虚假头结点),这个结点可以简化代码(不用先算出头结点了,而且一开始不需要判断List1和List2为null了)。

(有了dummy之后,所有的节点都变成拥有前置节点的节点了。所以就不用担心处理头节点这个特殊情况了。而且你最后需要返回的仅仅是dummy.next,不用花功夫去保持住你的头结点了)

(We insert a dummy head before the new list so we don’t have to deal with special cases such as initializing the new list’s head. Then the new list’s head could just easily be returned as dummy head’s next node.)

Solution

    //1. 循环
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        //有了dummyHead,就不需要下面两句了,而且也不用在l1和l2中找出头结点,
        //头结点直接用dummyHead.next表示。
        //if(l1==null)    return l2;
        //if(l2==null)    return l1;
        ListNode dummyHead=new ListNode(0);
        ListNode p=dummyHead;
        while(l1!=null && l2!=null){
            if(l1.val<l2.val){
                p.next=l1;
                l1=l1.next;
            }else{
                p.next=l2;
                l2=l2.next;
            }
            p=p.next;
        }
        p.next= l1==null? l2:l1;
        return dummyHead.next;
    }
    
    //2. 递归
    public ListNode mergeTwoLists2(ListNode l1, ListNode l2) {
        if(l1==null)    return l2;
        if(l2==null)    return l1;
        if(l1.val<l2.val){
            l1.next=mergeTwoLists(l1.next,l2);
            return l1;
        }else{
            l2.next=mergeTwoLists(l1,l2.next);
            return l2;
        }
    }

  

What I've learned

1. 学会使用dummyHead,注意dummyHead必须初始化,不能为null。

 

 More:【目录】LeetCode Java实现

 

转载于:https://www.cnblogs.com/yongh/p/10170706.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值