Merge Two Sorted Lists

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     ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) {
 2         // IMPORTANT: Please reset any member data you declared, as
 3         // the same Solution instance will be reused for each test case.
 4         if(l1 == NULL)
 5             return l2;
 6         if(l2 == NULL)
 7             return l1;
 8         ListNode *result, *head = NULL;
 9         if(l1->val < l2->val){
10             head = l1;
11             l1 = l1->next;
12         }            
13         else{
14             head = l2;
15             l2 = l2->next;
16         }
17         result = head;
18         while(l1 && l2){
19             if(l1->val < l2->val){
20                 result->next = l1;
21                 l1 = l1->next;
22             }
23             else{
24                 result->next = l2; 
25                 l2 = l2->next;
26             }
27             result = result->next;
28         }
29         if(l1 == NULL)
30             result->next = l2;
31         else
32             result->next = l1;
33         return head;
34     }
原文地址:https://www.cnblogs.com/waruzhi/p/3406076.html