Ideas
Use three cursors: cur points to the end of the merged list, L1,L2 is used to traverse two linked lists, and the smaller elements are added to the combined list.
Little Tricks
Using redundant head nodes can be used to determine the situation in a concise manner, where a linked list, or two, is an empty list.
thereby streamlining the code.
Plain Code
classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) {ListNode* Head, *ptr; if(!l1 &&!l2)returnNULL; if(!L1 && L2)returnL2; if(L1 &&!l2)returnL1; if(L1->val > l2->val) {Head=L2; L2= l2->Next; } Else{Head=L1; L1= l1->Next; } ptr=Head; while(L1 &&L2) { if(L1->val <= l2->val) {ptr->next =L1; L1= l1->Next; } Else{ptr->next=L2; L2= l2->Next; } ptr= ptr->Next; } if(L1) {ptr->next =L1; } Else{ptr->next =L2; } returnHead; }};
Optimized code
classSolution { Public: ListNode* Mergetwolists (listnode* L1, listnode*L2) {ListNode Dummy (0); ListNode*ptr = &dummy; while(L1 &&L2) { if(L1->val <= l2->val) {ptr->next =L1; L1= l1->Next; } Else{ptr->next=L2; L2= l2->Next; } ptr= ptr->Next; } if(L1) {ptr->next =L1; } Else{ptr->next =L2; } returnDummy.next; }};
#21 two linked lists after the merge sort