abc_begin

导航

21. Merge Two Sorted Lists【easy】

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 的代码

 

解法二和解法三都是递归,还没有完全弄明白……

 

posted on 2017-10-14 13:06  LastBattle  阅读(160)  评论(0编辑  收藏  举报