leetcode 148 排序链表
题目链接:https://leetcode-cn.com/problems/sort-list/
就是对一个链表进行排序。。
我采取得快排的思路,提交超过5%。。。看list标准库是用归并排序实现的,过几天改下的,现在先把链表快排的思路放上:
- 选择target(即基础点,左边的元素都小于target,右边的都大于target)
- 快指针从前往后,找到一个小于target,然后与low指针对换val(链表节点顺序不变,只改变其中的val)
- 递归处理左边和右边(以low为界)
1 /** 2 * Definition for singly-linked list. 3 * struct ListNode { 4 * int val; 5 * ListNode *next; 6 * ListNode() : val(0), next(nullptr) {} 7 * ListNode(int x) : val(x), next(nullptr) {} 8 * ListNode(int x, ListNode *next) : val(x), next(next) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 ListNode* sortList(ListNode* head) { 14 if(head==nullptr) return head; 15 sort(head, nullptr); 16 return head; 17 } 18 19 void sort(ListNode *begin, ListNode *end){ 20 if(begin == end) return; 21 ListNode *fast = begin->next, *low = begin; 22 int target = begin->val; 23 while(fast != end){ 24 if(fast->val < target){ 25 low = low->next; 26 swap(fast->val, low->val); 27 } 28 fast = fast->next; 29 } 30 swap(begin->val, low->val); 31 sort(begin, low); 32 sort(low->next, end); 33 } 34 };

浙公网安备 33010602011771号