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.
====================================================================================
One thing to mark. The expression below is wrong,
1 cur_node = new NodeList(x); 2 cur_node = cur_node->next;
the proper expression should be:
cur_node->next = new ListNode(x); cur_node = cur_node->next;
So the whole code will be like this. Remember that the root node IS NOT included into result.
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 * result_root = new ListNode(0); 13 ListNode * cur_node = result_root; 14 while(NULL != l1 || NULL != l2) { 15 if(NULL == l1 || (NULL != l1 && NULL != l2 && l2->val <= l1->val)) { 16 cur_node->next = new ListNode(l2->val); 17 l2 = l2->next; 18 }else{ 19 cur_node->next = new ListNode(l1->val); 20 l1 = l1->next; 21 } 22 cur_node = cur_node->next; 23 24 } 25 return result_root->next; 26 } 27 };