148. Sort List
Sort a linked list in O(n log n) time using constant space complexity.
链表的归并排序。
/** * 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 == NULL || head->next == NULL) return head; ListNode *tail = head, *mid = head, *pre = head; while (tail && tail->next) { pre = mid; mid = mid->next; tail = tail->next->next; } //change pre next to null, make two sub list(head to pre, p1 to p2) pre->next = NULL; ListNode *h1 = sortList(head); ListNode *h2 = sortList(mid); return merge(h1, h2); } ListNode* merge(ListNode *h1, ListNode *h2) { if (h1 == NULL) return h2; if (h2 == NULL) return h1; if (h1->val < h2->val) { h1->next = merge(h1->next, h2); return h1; } else { h2->next = merge(h1, h2->next); return h2; } } };
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步