-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInsertionSortList.cpp
70 lines (54 loc) · 1.03 KB
/
InsertionSortList.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
//Sort a linked list using insertion sort.
#include<stddef.h>
#include<climits>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class InsertionSortList {
public:
ListNode* insertionSortList(ListNode* head) {
if (!head) return NULL;
ListNode fh = ListNode(INT_MIN);
fh.next = head;
ListNode *pre = head, *cur = head, *t, *p, *nex;
while (cur)
{
nex = cur->next;
t = fh.next;
p = &fh;
while (t != cur&&t->val<cur->val)
{
t = t->next;
p = p->next;
}
if (t != cur)
{
p->next = cur;
cur->next = t;
pre->next = nex;
}
else
{
pre = cur;
}
cur = nex;
}
return fh.next;
//ListNode result(INT_MIN);
////result.next=head;
//while (head) {
// ListNode* iter = &result;
// while (iter->next && iter->next->val < head->val) {
// iter = iter->next;
// }
// ListNode* next = head->next;
// head->next = iter->next;
// iter->next = head;
// head = next;
//}
//return result.next;
}
};