-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathInsertion Sort List.cpp
79 lines (72 loc) · 1.59 KB
/
Insertion Sort List.cpp
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode *insertionSortList(ListNode *head) {
if(head==NULL)
return NULL;
ListNode* sorted_tail=head, *node, *prev, *curr;
while(sorted_tail->next!=NULL){
node = sorted_tail->next;
if(node->val >= sorted_tail->val){
sorted_tail=node;
}
else{
sorted_tail->next = node->next;
curr=head, prev = NULL;
while(node->val >= curr->val){
prev = curr;
curr = curr->next;
}
if(prev){
prev->next = node;
node->next = curr;
}
else{
node->next = curr;
head = node;
}
}
}
return head;
}
};
//naive version
class Solution1 {
public:
ListNode *insertionSortList(ListNode *head) {
if(head==NULL)
return NULL;
ListNode* r = new ListNode(head->val);
head = head->next;
while(head!=NULL){
r = insert(r,head->val);
}
return r;
}
ListNode* insert(ListNode* head, int value){
ListNode* prev = NULL;
while(head!=NULL && value > head->val){
prev = head;
head = head->next;
}
ListNode* new_node = new ListNode(value);
if(prev){
prev->next = new_node;
new_node->next = head;
return head;
}
else{
new_node->next = head;
return new_node;
}
}
};
int main(){
cout << "hello";
}