-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinsertionSortList.cpp
47 lines (41 loc) · 1.18 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
/********************************************************************
Copyright : CNIC
Author : LiuYao
Date : 2017-9-3
Description : leetcode 147. Insertion Sort List
********************************************************************/
#include <cstddef>
// Definition for singly-linked list.
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* insertionSortList(ListNode* head) {
if(!head || !head -> next) return head;
ListNode* newHead = new ListNode(0);
newHead -> next = head;
ListNode* p1 = newHead -> next, *p2 = head -> next, *last = newHead, *candinate = p2;
head -> next = NULL;
while(p2){
while(p1){
if(p1 -> val > candinate -> val) break;
last = p1;
p1 = p1 -> next;
}
last -> next = candinate;
p2 = p2 -> next;
candinate -> next = p1;
candinate = p2;
p1 = newHead -> next;
last = newHead;
}
return newHead -> next;
}
int main(){
ListNode* head = new ListNode(3);
head -> next = new ListNode(4);
head -> next -> next = new ListNode(1);
insertionSortList(head);
return 0;
}