merge two sorted list
1 class Solution { 2 public: 3 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 ListNode* root = new ListNode(-1); 7 ListNode* ptr = root; 8 while( l1!= NULL && l2 != NULL ) 9 { 10 if( l1->val <= l2->val ) 11 { 12 ptr->next = l1; 13 ptr = ptr->next; 14 l1 = l1->next; 15 } 16 else 17 { 18 ptr->next = l2; 19 ptr = ptr->next; 20 l2 = l2->next; 21 } 22 } 23 if( l1 != NULL ) 24 ptr->next = l1; 25 if( l2 != NULL ) 26 ptr->next = l2; 27 28 return root->next; 29 30 } 31 };
1 class Solution { 2 public: 3 ListNode *mergeTwoLists(ListNode *l1, ListNode *l2) { 4 // Start typing your C/C++ solution below 5 // DO NOT write int main() function 6 if( !l1 && !l2 ) return NULL; 7 if( !l1 ) return l2; 8 if( !l2 ) return l1; 9 ListNode *h = new ListNode(0); 10 11 h -> next = l1; 12 ListNode *p = h; 13 14 while( l1 && l2 ) 15 { 16 if( l1->val <= l2->val) 17 { 18 p = p->next; 19 l1 = l1->next; 20 } 21 else 22 { 23 24 p -> next = l2; 25 l2 = l2 -> next; 26 p -> next -> next = l1 ; 27 p = p->next; 28 } 29 } 30 if( l2 ) p->next = l2; 31 return h->next; 32 33 } 34 };
posted on 2013-07-04 13:26 jumping_grass 阅读(148) 评论(0) 收藏 举报
浙公网安备 33010602011771号