1. 程式人生 > >21. Merge Two Sorted Lists【easy】

21. Merge Two Sorted Lists【easy】

wol int while min st2 遞歸 merge listnode rst

21. Merge Two Sorted Lists【easy】

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.

解法一:

 1 /**
 2  * Definition for singly-linked list.
 3  * struct ListNode {
 4  *     int val;
 5  *     ListNode *next;
6 * ListNode(int x) : val(x), next(NULL) {} 7 * }; 8 */ 9 class Solution { 10 public: 11 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 12 if (l1 == NULL || l2 == NULL) { 13 return l1 ? l1 : l2; 14 } 15 16 ListNode * dummy = new
ListNode(INT_MIN); 17 ListNode * temp = dummy; 18 19 while (l1 && l2) { 20 if (l1->val > l2->val) { 21 dummy->next = l2; 22 l2 = l2->next; 23 } 24 else { 25 dummy->next = l1;
26 l1 = l1->next; 27 } 28 29 dummy = dummy->next; 30 } 31 32 if (l1 || l2) { 33 dummy->next = l1 ? l1 : l2; 34 } 35 36 return temp->next; 37 } 38 };

由於最後是弄到list1中,但是我們不知道list1還是list2的第一個元素關系,最後結果的list1中的頭結點可能會改變,所以需要引入dummy節點。

解法二:

 1 public ListNode mergeTwoLists(ListNode l1, ListNode l2){
 2         if(l1 == null) return l2;
 3         if(l2 == null) return l1;
 4         if(l1.val < l2.val){
 5             l1.next = mergeTwoLists(l1.next, l2);
 6             return l1;
 7         } else{
 8             l2.next = mergeTwoLists(l1, l2.next);
 9             return l2;
10         }
11 }

參考了@yangliguang 的代碼

解法三:

 1 public class Solution {
 2     public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
 3         if (l1 == null) return l2;
 4         if (l2 == null) return l1;
 5         
 6         ListNode handler;
 7         if(l1.val < l2.val) {
 8             handler = l1;
 9             handler.next = mergeTwoLists(l1.next, l2);
10         } else {
11             handler = l2;
12             handler.next = mergeTwoLists(l1, l2.next);
13         }
14         
15         return handler;
16     }
17 }

參考了@RunRunCode 的代碼

解法二和解法三都是遞歸,還沒有完全弄明白……

21. Merge Two Sorted Lists【easy】