-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path147.对链表进行插入排序.cpp
More file actions
81 lines (74 loc) · 1.97 KB
/
147.对链表进行插入排序.cpp
File metadata and controls
81 lines (74 loc) · 1.97 KB
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
80
/*
* @lc app=leetcode.cn id=147 lang=cpp
*
* [147] 对链表进行插入排序
*/
// @lc code=start
/**
* 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* move = head;
ListNode* tail = head; // 已排序链表尾节点。
while (move)
{
ListNode* move1 = head;
if (move1 == move) // 头结点
{
move = move->next;
continue;
}
else if (move1->val > move->val) // 插入到头结点
{
ListNode* buffer = head;
head = move;
move = move->next;
head->next = buffer;
tail->next = move;
}
else // 插入到其他位置。
{
while(move1->next != move)
{
if (move->val < move1->next->val)
{
break;
}
move1 = move1->next;
}
if (move1->next != move)
{
ListNode* buffer = move1->next;
move1->next = move;
move = move->next;
move1->next->next = buffer;
tail->next = move;
}
else
{
tail = move;
move = move->next;
}
}
/*
ListNode* i = head;
while (i)
{
cout << i->val << ":";
i = i->next;
}
cout << endl;
*/
}
return head;
}
};
// @lc code=end