File tree 2 files changed +37
-38
lines changed 2 files changed +37
-38
lines changed Original file line number Diff line number Diff line change
1
+ // Time: O(n^2)
2
+ // Space: O(1)
3
+
4
+ /* *
5
+ * Definition for singly-linked list.
6
+ * struct ListNode {
7
+ * int val;
8
+ * ListNode *next;
9
+ * ListNode(int x) : val(x), next(NULL) {}
10
+ * };
11
+ */
12
+ class Solution {
13
+ public:
14
+ ListNode *insertionSortList (ListNode *head) {
15
+ ListNode dummy{numeric_limits<int >::min ()};
16
+
17
+ auto curr = head;
18
+ ListNode *position = nullptr ;
19
+
20
+ while (curr) {
21
+ position = findInsertPosition (&dummy, curr->val );
22
+ ListNode *tmp = curr->next ;
23
+ curr->next = position->next ;
24
+ position->next = curr;
25
+ curr = tmp;
26
+ }
27
+
28
+ return dummy.next ;
29
+ }
30
+
31
+ ListNode* findInsertPosition (ListNode *head, int x) {
32
+ ListNode *prev = nullptr ;
33
+ for (auto curr = head; curr && curr->val <= x;
34
+ prev = curr, curr = curr->next );
35
+ return prev;
36
+ }
37
+ };
Load Diff This file was deleted.
You can’t perform that action at this time.
0 commit comments