-
Notifications
You must be signed in to change notification settings - Fork 0
/
147-InsertionSortList.cpp
55 lines (50 loc) · 1.52 KB
/
147-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
/*=============================================================================
# FileName: 147-InsertionSortList.cpp
# Desc:
# Author: qsword
# Email: huangjian1993@gmail.com
# HomePage:
# Created: 2015-05-11 10:19:58
# Version: 0.0.1
# LastChange: 2015-05-12 09:06:28
# History:
# 0.0.1 | qsword | init
=============================================================================*/
#include "leetcode.h"
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
//94ms
ListNode *insertionSortList(ListNode* head) {
if (!head || !(head->next)) {
return head;
}
ListNode *sorted = head, *tmp;
while (sorted->next) {
if (sorted->next->val < head->val) {
tmp = sorted->next;
sorted->next = tmp->next;
tmp->next = head;
head = tmp;
} else {
tmp = head;
while (tmp != sorted && tmp->next->val <= sorted->next->val) {
tmp = tmp->next;
}
if (tmp == sorted) {
sorted = sorted->next;
} else {
ListNode *unsorted = sorted->next;
sorted->next = unsorted->next;
unsorted->next = tmp->next;
tmp->next = unsorted;
}
}
}
return head;
}
};