Sort a linked list in O(n log n) time using constant space complexity.
Subscribe to see which companies asked this question
解法:这题和Insertion Sort List链表插入排序一样,都是要求对单链表进行排序,但是本题要求时间复杂度在O(nlogn),空间复杂度在O(1)。列出常用排序算法:冒泡排序、插入排序、选择排序、快速排序、堆排序、归并排序、基数排序、希尔排序等等,满足时间空间复杂度的有堆排序。但是对于链表,因为其不能随机存取,因此建堆时间复杂度可能会比较高。满足时间复杂度的还有快速排序和归并排序,快速排序中划分过程要求指针从两头往中间移动,这在链表中也不好实现。而归并排序的O(n)空间消耗在辅助数组,对于链表来说不需要这个辅助空间,因此可以用也只能用归并排序。
/** * 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 *slow = head, *fast = head; while (fast->next != NULL && fast->next->next != NULL) { slow = slow->next; fast = fast->next->next; } ListNode *head1 = head, *head2 = slow->next; slow->next = NULL; // 注意将链表分开为两部分 head1 = sortList(head1); head2 = sortList(head2); head = mergeTwoLists(head1, head2); return head; } private: ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) { if (l1 == NULL) return l2; if (l2 == NULL) return l1; ListNode* help = new ListNode(0); ListNode* head = help; while (l1 != NULL && l2 != NULL) { if (l1->val <= l2->val) { help->next = l1; l1 = l1->next; } else { help->next = l2; l2 = l2->next; } help = help->next; } if (l1 != NULL) help->next = l1; if (l2 != NULL) help->next = l2; return head->next; } };