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.
***Note***
Why would it will cause ERROR when not deleting line 15~17 or changing line 12 to
ListNode *pre_head = null; or ListNode *pre_head;
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 *pre_head = new ListNode(0); 13 ListNode *result = pre_head; 14 15 //if(!l1 && !l2) return result; 16 //if(!l1 && l2) return l2; 17 //if(l1 && !l2) return l1; 18 19 while(l1 || l2){ 20 if(!l1){ 21 while(l2){ 22 result->next = l2; 23 result = result->next; 24 l2 = l2->next; 25 } 26 break; 27 } 28 else if(!l2){ 29 while(l1){ 30 result->next = l1; 31 result = result->next; 32 l1 = l1->next; 33 } 34 break; 35 } 36 else{ 37 if(l1->val <= l2->val){ 38 result->next = l1; 39 l1 = l1->next; 40 } 41 else{ 42 result->next = l2; 43 l2 = l2->next; 44 } 45 } 46 result = result->next; 47 result->next = NULL; 48 } 49 return pre_head->next; 50 } 51 };
原文:http://www.cnblogs.com/amazingzoe/p/4435435.html