-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertionSortList.cpp
36 lines (36 loc) · 1.21 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
// https://leetcode.com/problems/insertion-sort-list/
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(head == NULL || head->next == NULL)return head;
ListNode *p = head->next, *pstart = new ListNode(0), *pend = head;
pstart->next = head; //为了操作方便,添加一个头结点
while(p != NULL) {
ListNode *tmp = pstart->next, *pre = pstart;
while(tmp != p && p->val >= tmp->val) {
tmp = tmp->next; pre = pre->next;
}
if(tmp == p)
pend = p;
else {
pend->next = p->next;
p->next = tmp;
pre->next = p;
}
p = pend->next;
}
head = pstart->next;
delete pstart;
return head;
}
};