1. Array Value Extraction & Built-In Sorting
Intuition
1. Collect all node values into a vector/list vals.
2. Sort vals in ascending order.
3. Traverse the linked list and overwrite each node.val with the sorted value.
When to apply: Quick, practical solution when extra O(N) space is permitted and node references need not remain intact.
Algorithm
- Traverse linked list and append values into array.
- Sort array using built-in dual-pivot Quicksort / Timsort.
- Traverse list again and overwrite values sequentially.
#include <iostream>#include <vector>#include <algorithm> 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* sortList(ListNode* head) { if (!head || !head->next) return head; std::vector<int> vals; ListNode* curr = head; while (curr != nullptr) { vals.push_back(curr->val); curr = curr->next; } std::sort(vals.begin(), vals.end()); curr = head; for (int v : vals) { curr->val = v; curr = curr->next; } return head; }}; int main() { ListNode* head = new ListNode(4, new ListNode(2, new ListNode(1, new ListNode(3)))); Solution sol; ListNode* res = sol.sortList(head); while (res != nullptr) { std::cout << res->val << " "; res = res->next; } std::cout << std::endl; return 0;}Time & Space Complexity
- Time complexity:
O(N log N)— Extracting values is O(N), sorting is O(N log N), and rewriting is O(N). Total time is O(N log N). - Space complexity:
O(N)— Allocates an auxiliary array holding all N values: O(N) space.