【LeetCode】21. Merge Two Sorted Lists

Difficulty: Easy

 More:【目錄】LeetCode Java實現html

Description

https://leetcode.com/problems/merge-two-sorted-lists/java

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.node

Example:post

Input: 1->2->4, 1->3->4
Output: 1->1->2->3->4->4

Intuition

合併兩個排序的鏈表題目徹底相同,能夠採用循環和遞歸來實現。循環的實現代碼中能夠使用一個dummyHead(虛假頭結點),這個結點能夠簡化代碼(不用先算出頭結點了,並且一開始不須要判斷List1和List2爲null了)。ui

(有了dummy以後,全部的節點都變成擁有前置節點的節點了。因此就不用擔憂處理頭節點這個特殊狀況了。並且你最後須要返回的僅僅是dummy.next,不用花功夫去保持住你的頭結點了)url

(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.)code

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。htm

 

 More:【目錄】LeetCode Java實現blog

相關文章
相關標籤/搜索