Leetcode: Sort list

Source: Internet
Author: User

Problem:


Sort a linked list in O (n log n) time using constant space complexity.


Solution:


First, the time complexity can reach the O (nlgn) sorting algorithm. There are three common types: heap sorting, Merge Sorting, and quick sorting,


For linked lists, sorting by heap is obviously unlikely. Therefore, we can merge them or sort them quickly. Because we merge two linked lists, we only use


Modify the corresponding pointer, so it can achieve space complexity O (1). The following is the sort of linked lists using the merge sort idea.


Solution:

Class solution {public: listnode * sortlist (listnode * P) {If (P = NULL | p-> next = NULL) return P; // Add a header node, avoid the case where rear is empty during merging. listnode * head = new listnode (-1), * q = head; head-> next = P; int CNT = 0; while (p) {++ CNT; P = p-> next; If (CNT % 2 = 0) q = Q-> next;} p = Q-> next, Q-> next = NULL; // recursively sort the left and right sides of the head-> next = q = sortlist (Head-> next); P = sortlist (p); // merge q = merge (Head, p); free (head); Return Q;} listnode * Merge (listnode * head, listnode * r) {listnode * l = head-> next, * rear = head; while (L & R) {If (L-> Val <r-> Val) {rear-> next = L; L = L-> next, rear = rear-> next;} else {rear-> next = r; r = r-> next, rear = rear-> next;} while (l) {rear-> next = L; L = L-> next, rear = rear-> next;} while (r) {rear-> next = R; R = r-> next, rear = rear-> next;} return head-> next ;}};


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.