#21 two linked lists after the merge sort

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.