【LeetCode】21. Merge Two Sorted Lists

Difficulty: Easy

 More:【目录】LeetCode Java实现

Description

https://leetcode.com/problems/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

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