-
Notifications
You must be signed in to change notification settings - Fork 25
Expand file tree
/
Copy pathinsertion_sort_list.cpp
More file actions
49 lines (43 loc) · 919 Bytes
/
insertion_sort_list.cpp
File metadata and controls
49 lines (43 loc) · 919 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
ListNode *sorted = NULL;
ListNode *node = NULL;
while (head != NULL) {
node = head->next;
insert_node(sorted, head);
head = node;
}
return sorted;
}
protected:
void insert_node(ListNode *&head, ListNode *&node) {
if (NULL == head) {
head = node;
head->next = NULL;
}
else {
if (node->val <= head->val) {
node->next = head;
head = node;
}
else {
ListNode *prev = NULL;
ListNode *next = head;
while (next != NULL) {
if (next->val < node->val) {
prev = next;
next = next->next;
}
else {
prev->next = node;
node->next = next;
return;
}
}
prev->next = node;
node->next = NULL;
}
}
}
};