【37】21. Merge Two Sorted Lists

21. Merge Two Sorted Lists

  • Total Accepted: 190954
  • Total Submissions: 500570
  • Difficulty: Easy
  • Contributors: Admin

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.

Solution 1: 

新建一个链表,把两个链表中较小的一个链到新链表上。

 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         ListNode* dummy = new ListNode(-1);
13         ListNode* curr = dummy;
14         while(l1 && l2){
15             if(l1 -> val < l2 -> val){
16                 curr -> next = l1;
17                 l1 = l1 -> next;
18                 curr = curr -> next;
19             }else{
20                 curr -> next = l2;
21                 l2 = l2 -> next;
22                 curr = curr -> next;
23             }
24         }
25         if(l1){
26             curr -> next = l1;
27         }
28         if(l2){
29             curr -> next = l2;
30         }
31         return dummy -> next;
32     }
33 };

Solution 2: recursive

除了base case:l1 或l2有一个为空的情况下,就返回另一个。

核心是比较l1与l2的值,如果l1的值小于l2,则对于l1 -> next 和l2调用递归函数,把返回值赋予l1 -> next; 反之,同理。

 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) return l2;//base case
13         if(!l2) return l1;//base case
14         if(l1 -> val < l2 -> val){
15             //return mergeTwoLists(l1 -> next, l2);
16             l1 -> next = mergeTwoLists(l1 -> next, l2);
17             return l1;
18         }else{
19             l2 -> next = mergeTwoLists(l1, l2 -> next);
20             return l2;
21         }
22     }
23 };

 

 

 

 

 

 

posted @ 2017-02-09 08:01  会咬人的兔子  阅读(126)  评论(0编辑  收藏  举报