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 ListNode *dummy = new ListNode(0); 13 ListNode *ret = NULL; 14 15 16 ListNode *p1 = l1; 17 ListNode *p2 = l2; 18 19 ListNode *p = dummy; 20 21 while(p1 && p2){ 22 if (p1->val < p2->val){ 23 p->next = p1; 24 p1 = p1->next; 25 }else{ 26 p->next = p2; 27 p2 = p2->next; 28 } 29 p = p->next; 30 } 31 32 p1 = (!p1) ? p2 : p1; 33 34 while (p1){ 35 p->next = p1; 36 // don't forget to move p1 !! 37 p1 = p1->next; 38 p = p->next; 39 } 40 41 ret = dummy->next; 42 delete dummy; 43 return ret; 44 } 45 };