题解 | #单链表的排序#记录
单链表的排序
https://www.nowcoder.com/practice/f23604257af94d939848729b1a5cda08
/**
* struct ListNode {
* int val;
* struct ListNode *next;
* ListNode(int x) : val(x), next(nullptr) {}
* };
*/
class Solution {
public:
/**
* 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
*
*
* @param head ListNode类 the head node
* @return ListNode类
*/
ListNode* sortInList(ListNode* head) {
// write code here
vector<ListNode*> lists;
ListNode *p;
while(head){
p = head->next;
head->next = nullptr;
lists.push_back(head);
head = p;
}
return div(lists, 0, lists.size()-1);
}
//归并排序
ListNode* div(vector<ListNode*>& lists, int l, int r) {
if (l > r) return nullptr;
if (l == r) return lists[l];
int m = (l + r) / 2;
return Merge(div(lists, l, m), div(lists, m + 1, r));
}
ListNode* Merge(ListNode* pHead1, ListNode* pHead2) {
// write code here
ListNode* head;
ListNode* p2, *p1, *s;
if (pHead1 && pHead2) {
if (pHead1->val > pHead2->val) {
head = pHead1;
p2 = pHead2;
} else {
head = pHead2;
p2 = pHead1;
}
} else if (pHead1) {
return pHead1;
} else return pHead2;
p1 = head;
//双指针,p1,p2,比大小前插,小则后移
head = p2;
p2 = p2->next;
head->next = p1;
s = head;
while (p2) {
//
if (p2->val <= p1->val) {
s->next = p2;
p2 = p2->next;
s = s->next;
s->next = p1;
} else {
p1 = p1->next;
s = s->next;
if (!p1) {
s->next = p2;
return head;
}
}
}
return head;
}
};
时间复杂度和空间复杂度应该都符合题意。
准备尝试快速排序,防丢失

