Leetcode Merge Sorted Lists merging sort

Source: Internet
Author: User

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 classSolution {Ten  Public: OneListNode *mergetwolists (ListNode *l1, ListNode *L2) { A         if(l1==0)returnL2; -         if(l2==0)returnL1; -ListNode *start=0, *end=0; the         if(l1->val<l2->val) { -Start=end=L1; -L1=l1->Next; -         } +         Else{ -Start=end=L2; +L2=l2->Next; A         } at          while(l1!=0&&l2!=0){ -             if(l1->val<l2->val) { -end->next=L1; -L1=l1->Next; -             } -             Else{ inend->next=L2; -L2=l2->Next; to             } +End=end->Next; -         } the         if(l1==0) *end->next=L2; $         ElsePanax Notoginsengend->next=L1; -         returnstart;  the     } +};

Test instructions: Merges two ordered linked lists into an ordered list and returns.

Idea: no recursion! The first value compares the size, and start points to the small one, as the last return address. Li keeps comparing the L2 to the end pointer after each comparison, and end starts from start. Finally, the two linked lists will be strung together and ordered. Analogy: Two hands holding an orderly poker, each pick out the hands of the smallest points, put on the table, and finally they from the bottom to the top of the stack in an orderly manner. Then one hand shines first, then you can put the rest of the cards directly on the table.

Leetcode Merge Sorted Lists merging 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.