1、题目描述
2、题目分析
题目要求合并有序的两个链表,要求不能额外申请空间。
3、代码
1 ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { 2 if( l1 == NULL )return l2; 3 if( l2 == NULL )return l1; 4 if( l1 == NULL && l2 == NULL ) return NULL; 5 ListNode* r = ( l1->val <= l2->val )?l1:l2; 6 if( l1->val <= l2->val ){ 7 l1 = l1->next; 8 }else{ 9 l2 = l2->next; 10 } 11 12 ListNode* pm = r ; 13 while( l1 != NULL && l2 != NULL ){ 14 if( l1->val <= l2->val ){ 15 pm->next = l1; 16 l1 = l1->next; 17 }else{ 18 pm->next = l2; 19 l2 = l2->next; 20 } 21 pm = pm->next; 22 } 23 24 if( l1 != NULL ){ 25 pm->next = l1; 26 } 27 if( l2 != NULL ){ 28 pm->next = l2; 29 } 30 31 return r; 32 }