The list is sorted using O (n log n) time complexity and constant-level spatial complexity.
See: https://leetcode.com/problems/sort-list/description/
Method One: Merge sort
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {public:listnode* sortlist (listnode* head) {if (head==nullptr| | HEAD->NEXT==NULLPTR) {return head; } listnode* Slow=head; listnode* Fast=head; listnode* mid=nullptr; while (Fast&&fast->next) {mid=slow; slow=slow->next; fast=fast->next->next; } mid->next=nullptr; Return Mergehelper (Sortlist (head), sortlist (slow)); } listnode* Mergehelper (listnode* low,listnode* high) {listnode* helper=new ListNode (-1); listnode* Cur=helper; while (Low&&high) {if (low->val Method Two: Quick sort
/** * Definition for singly-linked list. * struct ListNode {* int val; * ListNode *next; * ListNode (int x): Val (x), Next (NULL) {} *}; */class Solution {public:listnode* sortlist (listnode* head) {if (head==nullptr| | HEAD->NEXT==NULLPTR) {return head; } quickSort (HEAD,NULLPTR); return head; } void QuickSort (listnode* begin,listnode* end) {if (begin!=end) {listnode* Sep=getseperat or (begin,end); QuickSort (BEGIN,SEP); QuickSort (Sep->next,end); }} listnode* Getseperator (listnode* begin,listnode* end) {listnode* first=begin; listnode* second=begin->next; int key=begin->val; while (Second!=end) {if (Second->val<key) {first=first->next; Swap (First,second); } second=second->next; } swap (First,begin); Return First } void Swap (listnode* a,listnode* b) {int tmp=a->val; a->val=b->val; b->val=tmp; }};
148 Sort and Quick sort on list lists