[LeetCode] Sort List
Posted immjc
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[LeetCode] Sort List相关的知识,希望对你有一定的参考价值。
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3 Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0 Output: -1->0->3->4->5
对链表进行排序
1. 要求算法复杂度为O(nlogn),只有使用快速排序,归并排序,堆排序。
2. 选择归并排序。
3. 对链表进行递归划分后合并即可。
递归
// Iterator /** * 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 == NULL || head->next == NULL) return head; ListNode* fast = head; ListNode* slow = head; ListNode* prev = NULL; while (fast && fast->next) { prev = slow; fast = fast->next->next; slow = slow->next; } prev->next = NULL; ListNode* l1 = sortList(head); ListNode* l2 = sortList(slow); return mergeList(l1, l2); } ListNode* mergeList(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; if (l1->val < l2->val) { l1->next = mergeList(l1->next, l2); return l1; } else { l2->next = mergeList(l1, l2->next); return l2; } } };
迭代
// Recursion /** * 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 == NULL || head->next == NULL) return head; ListNode* fast = head; ListNode* slow = head; ListNode* prev = NULL; while (fast && fast->next) { prev = slow; fast = fast->next->next; slow = slow->next; } prev->next = NULL; ListNode* l1 = sortList(head); ListNode* l2 = sortList(slow); return mergeList(l1, l2); } ListNode* mergeList(ListNode* l1, ListNode* l2) { ListNode* dummy = new ListNode(0); ListNode* curr = dummy; while (l1 && l2) { if (l1->val < l2->val) { curr->next = l1; l1 = l1->next; } else { curr->next = l2; l2 = l2->next; } curr = curr->next; } if (l1) curr->next = l1; if (l2) curr->next = l2; return dummy->next; } };
以上是关于[LeetCode] Sort List的主要内容,如果未能解决你的问题,请参考以下文章
Leetcode147. Insertion Sort List
LeetCode 147. Insertion Sort List