在使用O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
详见:https://leetcode.com/problems/sort-list/description/
方法一:归并排序
/** * 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<high->val) { cur->next=low; low=low->next; } else { cur->next=high; high=high->next; } cur=cur->next; } cur->next=low?low:high; return helper->next; } };
方法二:快速排序
/** * 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=getSeperator(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; } };
原文地址:https://www.cnblogs.com/xidian2014/p/8727493.html
时间: 2024-11-10 18:50:22