一、题目
二、题解
利用归并的思想对链表进行排序,首先找到链表的中间节点通过getMid快慢指针,然后进行归并,在归并完成进行两个链表的合并操作
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* getMid(ListNode* head) {
if (head == nullptr) return nullptr;
ListNode* slow = head;
ListNode* fast = head;
while (fast != nullptr && fast->next != nullptr && fast->next->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
}
ListNode* merge1(ListNode* l1, ListNode* l2) {
ListNode* newHead = new ListNode(0);
ListNode* cur = newHead;
while (l1 != nullptr && l2 != nullptr) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
}
else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1 != nullptr) cur->next = l1;
if (l2 != nullptr) cur->next = l2;
return newHead->next;
}
ListNode* merge(ListNode* head) {
if (head == nullptr || head->next == nullptr) return head;
ListNode* t = getMid(head);
ListNode* mid = t->next;
t->next = nullptr;
ListNode* l1 = merge(head);
ListNode* l2 = merge(mid);
return merge1(l1, l2);
}
ListNode* sortList(ListNode* head) {
return merge(head);
}
};