class Solution {
public:
// 归并排序
ListNode* merge(ListNode* a, ListNode* b) {
if (a == NULL) {
return b;
}
if (b == NULL) {
return a;
}
// 这里实质上就是将两个有序链表链接起来,如1->3->5 和 2->8->10 链成 1->2->3->5->8->10
ListNode* new_head = NULL;
ListNode* cur = NULL;
if (a->val <= b->val) {
new_head = a;
a = a->next;
} else {
new_head = b;
b = b->next;
}
cur = new_head;
while(a && b) {
if (a->val <= b->val) {
cur->next = a;
cur = a;
a = a->next;
} else {
cur->next = b;
cur = b;
b = b->next;
}
}
if(a) {
cur->next = a;
}
if (b) {
cur->next = b;
}
return new_head;
}
ListNode* sortList(ListNode* head) {
// 归并排序
if (head == NULL || head->next == NULL) {
return head;
}
ListNode* first = head;
ListNode* mid = getMid(head);
ListNode* second = mid->next;
mid->next = NULL; //将链表分为两段
first = sortList(first);
second = sortList(second);
return merge(first, second);
}
//将链表平分为两段,返回第一段末尾 例如:5个点返回2号点,6个点返回3号点
ListNode* getMid(ListNode* head) {
ListNode* slow = head;
ListNode* fast = head->next;
while(fast && fast->next) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
};
复制代码
排序链表(LeetCode)
最新推荐文章于 2024-06-22 21:53:36 发布