148. Sort List
https://leetcode.com/problems/sort-list/description/
Thoughts
Code
/*
* @lc app=leetcode id=148 lang=cpp
*
* [148] Sort List
*/
// @lc code=start
/**
* 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 == nullptr || head->next == nullptr) return head;
const auto mid = [&]() {
auto slow = head, fast = head->next;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
}
return slow;
};
auto slow = mid(), next = slow->next;
auto r = sortList(slow->next);
slow->next = nullptr;
auto l = sortList(head);
ListNode *dummy = new ListNode(-1), *cur = dummy;
while (l != nullptr || r != nullptr) {
if (r == nullptr || l != nullptr && l->val <= r->val) {
cur->next = l;
l = l->next;
} else if (l == nullptr || r != nullptr && r->val <= l->val) {
cur->next = r;
r = r->next;
}
cur = cur->next;
}
return dummy->next;
}
};
// @lc code=end
Analysis
Last updated