Skip to content

Commit e7cd8df

Browse files
committed
Update and rename insertionSortList.cpp to insertion-sort-list.cpp
1 parent 416f9de commit e7cd8df

File tree

2 files changed

+37
-38
lines changed

2 files changed

+37
-38
lines changed

C++/insertion-sort-list.cpp

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
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+
};

C++/insertionSortList.cpp

Lines changed: 0 additions & 38 deletions
This file was deleted.

0 commit comments

Comments
 (0)