Sort----List of linked list by merge sort

Source: Internet
Author: User

The merge sort of the linked list (linklist merge sort)

First of all, if there are two ordered (sorted) linked list ListNode *a, and ListNode *b, how to merge into an ordered list?

ListNode * mergetwolists (ListNode *l1, ListNode *L2) {ListNode*head =NewListNode (-1); ListNode*p =Head;  for(;l1&&l2; p = p->next) {           if(L1->val <l2->val) {P->next =L1; L1=l1->Next; }           Else{p->next =L2; L2=l2->Next; }} P->next = l1!=nullptr?L1:l2; returnHead->Next; }

So the idea of a single-linked list is as follows: The same is the Division method

1. Find the midpoint node of a linked list and break it into two linked list from the point node.

2. The first half of the linked list and the second half of the list of linked list of the merge sort.

3. Get a list of two parts that have been sorted, and finally merge the linked list

The procedure is as follows: Leetcode accepted

/** Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x) : Val (x), Next (NULL) {}}; */classSolution { Public: ListNode* Sortlist (listnode*head) {    if(head==nullptr| | Head->next ==nullptr)returnHead; //get the Len of the listListNode * Fast =Head; ListNode* Slow =Head;  while(fast->next!=nullptr&&fast->next->next!=nullptr) {Fast= fast->next->Next; Slow= slow->Next; } Fast=slow; Find the mid of the linklist slow= slow->Next; Fast->next = nullptr;//cut the list to the parts;ListNode*L1 =Sortlist (head); ListNode*L2 =sortlist (slow); returnmergetwolists (L1,L2); } ListNode* Mergetwolists (ListNode *l1, ListNode *L2) {ListNode*head =NewListNode (-1); ListNode*p =Head;  for(;l1&&l2; p = p->next) {           if(L1->val <l2->val) {P->next =L1; L1=l1->Next; }           Else{p->next =L2; L2=l2->Next; }} P->next = l1!=nullptr?L1:l2; returnHead->Next; }    };

Sort----List of linked list by 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.