-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertion Sort List.cpp
59 lines (55 loc) · 1.25 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
#include <iostream>
using namespace std;
/**
* Definition for singly-linked list.
*/
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *dummy = new ListNode(-1);
dummy->next = head;
ListNode *cur1, *cur2, *last, *tmp;
for(cur1 = head; cur1 != NULL; ) {
if(cur1->next && cur1->next->val < cur1->val) {
//tmp = cur1->next->next;
last = dummy;
while(last->next && last->next->val <= cur1->next->val) {
last = last->next;
}
tmp = last->next;
last->next = cur1->next;
cur1->next = cur1->next->next;
last->next->next = tmp;
}
else {
cur1 = cur1->next;
}
}
return dummy->next;
}
};
ListNode *createList(int len) {
ListNode *dummy = new ListNode(-1);
ListNode *last = dummy;
for(int i = len; i >= 0; i--) {
last->next = new ListNode(i);
ListNode *tmp = last->next;
last = last->next;
}
return dummy->next;
}
int main() {
ListNode *head = createList(5);
Solution s;
head = s.insertionSortList(head);
while(head) {
cout << head->val << endl;
head = head->next;
}
return 0;
}