LeetCode OJ Sort List

来源:互联网 发布:淘宝dsr计算器 编辑:程序博客网 时间:2024/06/03 21:29

Sort List

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


先使用了快速排序,结果超时,后改为归并排序才Accepted。

快速排序:


class Solution {public:ListNode *sortList(ListNode *head) {QuickSortList(head, NULL);return head;}void QuickSortList(ListNode *head, ListNode *last){if (head == NULL || head == last)return;ListNode *slow = head;ListNode *fast = head->next;while (fast != last) {           //最后一个节点last不比较,或者为上一次的分割节点 或者为 NULLif (fast->val < head->val) {slow = slow->next;exch(&slow->val, &fast->val);}fast = fast->next;}exch(&head->val, &slow->val);QuickSortList(head, slow);QuickSortList(slow->next, last);  //slow->next 至多和 last 相等, 不会到last之后}void exch(int *a, int *b){int t = *a;*a = *b;*b = t;}};




归并排序:

class Solution {public:  ListNode *sortList(ListNode *head) {if (head == NULL || head->next == NULL)return head;ListNode *pOneStep = head;ListNode *pTwoStep = head;while (pTwoStep->next != NULL && pTwoStep->next->next != NULL) {pOneStep = pOneStep->next;pTwoStep = pTwoStep->next->next;}pTwoStep = pOneStep->next;pOneStep->next = NULL;pOneStep = sortList(head);pTwoStep = sortList(pTwoStep);return merge(pOneStep, pTwoStep);}ListNode *merge(ListNode *pOne, ListNode *pTwo){ListNode head(0);ListNode *p = &head;while (pOne != NULL && pTwo != NULL) {if (pOne->val <= pTwo->val) {p->next = pOne;p = pOne;pOne = pOne->next;}else {p->next = pTwo;p = pTwo;pTwo = pTwo->next;}}p->next = (pOne == NULL) ? pTwo : pOne;return head.next;}};


0 0
原创粉丝点击