单链表的排序_牛客题霸_牛客网 (nowcoder.com)
参考分治思想,双链表和并思想
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
class Solution {
public:
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
if (pHead1 == nullptr) return pHead2;
if (pHead2 == nullptr) return pHead1;
ListNode* head = new ListNode(0);
ListNode* res = head;
while (pHead1 != nullptr && pHead2 != nullptr) {
if (pHead1->val <= pHead2->val) {
res->next = pHead1;
pHead1 = pHead1->next;
} else {
res->next = pHead2;
pHead2 = pHead2->next;
}
res = res->next;
}
if (pHead1) res->next = pHead1;
else if (pHead2) res->next = pHead2;
return head->next;
}
ListNode* sortInList(ListNode* head) {
// write code here
if (head == nullptr || head->next == nullptr) {
return head;
}
//准备三个指针,快指针right每次走两步,慢指针mid每次走一步,前序指针left每次跟在mid前一个位置。三个指针遍历链表,当快指针到达链表尾部的时候,慢指针mid刚好走了链表的一半,正好是中间位置。
ListNode* left = head;
ListNode* mid = head->next;
ListNode* right = head->next->next;
while (right != nullptr && right->next != nullptr) {
left = left->next;
mid = mid ->next;
right = right->next->next;
}
//从left位置将链表断开,刚好分成两个子问题开始递归
left->next = nullptr;
return Merge(sortInList(head), sortInList(mid));
}
};
- 时间复杂度:O(nlog2n),每级划分最坏需要遍历链表全部元素,因此为O(n),每级合并都是将同级的子问题链表遍历合并,因此也为O(n),分治划分为二叉树型,一共有O(log2n)层,因此复杂度为O((n+n)∗log2n)=O(nlog2n)
- 空间复杂度:O(log2n),递归栈的深度最坏为树型递归的深度,log2n层