-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path147_insertion_sort_list.cc
52 lines (48 loc) · 1.15 KB
/
147_insertion_sort_list.cc
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
#include <vector>
#include <algorithm>
#include <string>
#include <map>
#include <set>
#include <iostream>
#include <tuple>
#include <queue>
#include <stack>
using namespace::std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode *ptr = head, *new_head = head;
while (ptr) {
ListNode* next = ptr->next;
if (next == nullptr)
break;
if (next->val < ptr->val) {
ptr->next = next->next;
ListNode *ptr2 = new_head, *ptr3 = nullptr;
while (ptr2->val < next->val) {
ptr3 = ptr2;
ptr2 = ptr2->next;
}
if (ptr2 == new_head) {
next->next = ptr2;
new_head = next;
} else {
ptr3->next = next;
next->next = ptr2;
}
} else {
ptr = ptr->next;
}
}
return new_head;
}
};
int main()
{
return 0;
}