← Home

148. Sort List

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
greedyC++Markdown
148

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 148. Sort List, the solution in this repository is mainly a greedy solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: greedy.

Guide

When?

This is the kind of solution you want when the problem has structure hiding inside a messy-looking input. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The important function names to track are merge, sortList.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • Sorting is used to make local choices comparable, so the later scan does not have to rediscover order.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(n) to O(n log n), depending on the dominant loop or data structure operation
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//Runtime: 68 ms, faster than 32.71% of C++ online submissions for Sort List.
02//Memory Usage: 12.7 MB, less than 27.50% of C++ online submissions for Sort List.
03/**
04 * Definition for singly-linked list.
05 * struct ListNode {
06 *     int val;
07 *     ListNode *next;
08 *     ListNode(int x) : val(x), next(NULL) {}
09 * };
10 */
11class Solution {
12public:
13//     void merge(ListNode* a, ListNode* b){
14//         ListNode *newHead = new ListNode(0);
15//         ListNode *cur = newHead;
16        
17//         while(a && b){
18//             if(a->val <= b.val){
19//                 cur->val = a->val;
20//                 a = a->next;
21//             }else
22//                 cur->val = b->val;
23//                 b = b->next;
24//             }
25//         }
26        
27//         if(a){
28//             cur->next = a;
29//         }else if(b){
30//             cur->next = b;
31//         }
32
33//         return newHead;
34//     };
35    
36    ListNode* sortList(ListNode* head) {
37        if(!head) return head;
38        vector<int> arr;
39        ListNode* cur = head;
40        
41        while(cur){
42            arr.push_back(cur->val);
43            cur = cur->next;
44        }
45        
46        sort(arr.begin(), arr.end());
47        
48        cur = head;
49        int i = 0;
50        while(cur){
51            cur->val = arr[i++];
52            cur = cur->next;
53        }
54        
55        return head;
56    }
57};
58
59//merge sort
60//https://leetcode.com/problems/sort-list/discuss/46714/Java-merge-sort-solution
61//use new
62//Runtime: 124 ms, faster than 16.37% of C++ online submissions for Sort List.
63//Memory Usage: 48.8 MB, less than 5.00% of C++ online submissions for Sort List.
64//don't use new to speed up
65//Runtime: 72 ms, faster than 26.62% of C++ online submissions for Sort List.
66//Memory Usage: 26.7 MB, less than 5.00% of C++ online submissions for Sort List.
67/**
68 * Definition for singly-linked list.
69 * struct ListNode {
70 *     int val;
71 *     ListNode *next;
72 *     ListNode(int x) : val(x), next(NULL) {}
73 * };
74 */
75class Solution {
76public:
77    ListNode* merge(ListNode* a, ListNode* b){
78        ListNode *newHead = new ListNode(0);
79        ListNode *cur = newHead;
80        
81        // cout << "in merge a: " << endl;
82        cur = a;
83        while(cur){
84            // cout << cur->val << " ";
85            cur = cur->next;
86        }
87        // cout << endl;
88        
89        // cout << "in merge b: " << endl;
90        // cur = b;
91        // while(cur){
92        //     cout << cur->val << " ";
93        //     cur = cur->next;
94        // }
95        // cout << endl;
96        
97        cur = newHead;
98        
99        // cout << "building list: " << endl;
100        while(a && b){
101            if(a->val <= b->val){
102                //use new -> time and space specified in first two rows
103                // cur->next = new ListNode(a->val);
104                //not use new -> time and space specified in second two rows
105                cur->next = a;
106                // cout << a->val << " ";
107                a = a->next;
108            }else{
109                // cur->next = new ListNode(b->val);
110                cur->next = b;
111                // cout << b->val << " ";
112                b = b->next;
113            }
114            cur = cur->next;
115        }
116        
117        //Method 1 to add remaining list
118//         while(a){
119//             cur->next = new ListNode(a->val);
120//             cout << a->val << " ";
121//             a = a->next;
122//             cur = cur->next;
123//         }
124        
125//         while(b){
126//             cur->next = new ListNode(b->val);
127//             cout << b->val << " ";
128//             b = b->next;
129//             cur = cur->next;
130//         }
131        
132        //Method 2 to add remaining list
133        if(a){
134            cur->next = a;
135        }else if(b){
136            cur->next = b;
137        }
138        
139        // cout << endl;
140        
141        // cout << "list built: " << endl;
142        // cur = newHead->next;
143        // while(cur){
144        //     cout << cur->val << " ";
145        //     cur = cur->next;
146        // }
147        // cout << endl;
148
149        return newHead->next;
150    };
151    
152    ListNode* sortList(ListNode* head) {
153        //length 0 or length 1, we cannot split anymore
154        if(!head || !head->next) return head;
155        
156        // cout << "current list: " << endl;
157        ListNode* cur = head;
158        while(cur){
159            // cout << cur->val << " ";
160            cur = cur->next;
161        }
162        // cout << endl;
163        
164        //split list
165        ListNode *slow = head, *fast = head;
166        ListNode *slowPrev; //used to cut the list into half
167        
168        while(fast && fast->next){
169            slowPrev = slow;
170            
171            slow = slow->next;
172            fast = fast->next->next;
173        }
174        
175        /*
176        now "head" and "slow" are the head of two lists,
177        we need to split them by setting "slow"'s previous node's next to nullptr
178        */
179        slowPrev->next = nullptr;
180        
181        //sort the splitted lists
182        head = sortList(head);
183        slow = sortList(slow);
184        
185        return merge(head, slow);
186    }
187};

Cost

Complexity

Time
O(n) to O(n log n), depending on the dominant loop or data structure operation
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.