【LeetCode】21. Merge Two Sorted Lists
阿新 • • 發佈:2018-12-24
code cin 開始 判斷 icu spec 合並 fir wol
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實現
【LeetCode】21. Merge Two Sorted Lists