148:sort list "Sort" of "linked list"

Source: Internet
Author: User

Title Link: https://leetcode.com/problems/sort-list/

/* Test Instructions: Sort the list *//** * Ideas: Merge sort * Divide: Divide the list into two segments: with slow and fast pointers, slow only one step at a time, fast every time * walk two steps. When fast is empty, the slow is located in the middle of the list.  * Merge: Two simple linked list merge */class solution {public:void Show (ListNode *head) {while (head! = NULL) {cout            << head->val << "";        Head = head->next;    } cout << Endl;        } ListNode *merge (ListNode *heada, ListNode *headb) {ListNode *root = new ListNode (0);        ListNode *p = root;                while (Heada && headb) {if (Heada->val <= headb->val) {p->next = Heada;            Heada = heada->next;                } else {p->next = headb;            HEADB = headb->next;        } p = p->next;            } while (Heada) {p->next = Heada;            p = p->next;        Heada = heada->next;            } while (headb) {p->next = headb;           p = p->next; HEADB = headb->next;        } ListNode *res = root->next;        Delete root;    return res;        } ListNode *mergesort (ListNode *head) {///Only one node if (head = = NULL | | head->next = NULL) return head;            ListNode *slow = head;            Slow pointer ListNode *fast = head->next->next;//fast pointer while (FAST! = NULL && Fast->next! = null) {            slow = slow->next;        Fast = fast->next->next;        } ListNode *heada = head;        ListNode *headb = slow->next;      Slow->next = NULL;        Disconnect the list Heada = MergeSort (Heada);        HEADB = MergeSort (HEADB);    Return Merge (Heada, headb);        } listnode* sortlist (listnode* head) {if (head = = NULL | | head->next = = NULL) return head;    Return MergeSort (head); }};

  

148:sort list "Sort" of "linked list"

Related Article

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.