- Notifications
You must be signed in to change notification settings - Fork 135
/
Copy pathleetcode147-insertion-sort-list.cpp
62 lines (57 loc) · 1.72 KB
/
leetcode147-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
#include<iostream>
#include<algorithm>
usingnamespacestd;
/** Definition for singly-linked list. */
structListNode {
int val;
ListNode *next;
ListNode() : val(0), next(nullptr) {}
ListNode(int x) : val(x), next(nullptr) {}
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
classSolution {
public:
ListNode* insertionSortList(ListNode* head) {
ListNode* fakeNode = newListNode(INT_MIN); /* 输入的链表中有0、负数之类的,这里用 INT_MAX比较合理 */
ListNode *p = fakeNode, *q = fakeNode;
ListNode* cur = head;
while (cur)
{
if (q->val < cur->val)
{
q->next = cur;
q = q->next;
cur = cur->next;
}
else
{
q->next = cur->next;
while (p->next != nullptr && p->next->val < cur->val)
p = p->next; /* 指针p 不断向前, 找需要插入的位置, 找到时停下 */
cur->next = p->next;
p->next = cur;
p = fakeNode; /* 插入排序: 每来1个新数, 都需要将它与已排序的每一个数都比较一次, 所以需要拉到开头供下次使用 */
cur = q->next;
}
}
return fakeNode->next;
}
};
// Test
intmain()
{
Solution sol;
ListNode *head = newListNode(4);
head->next = newListNode(2);
head->next->next = newListNode(3);
head->next->next->next = newListNode(1);
head->next->next->next->next = NULL;
auto res = sol.insertionSortList(head);
ListNode *p = res;
while (p != NULL)
{
cout << p->val << endl;
p = p->next;
}
return0;
}