forked from haoel/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
insertionSortList.cpp
90 lines (75 loc) · 1.91 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
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
81
82
83
84
85
86
87
88
89
90
// Source : https://oj.leetcode.com/problems/insertion-sort-list/
// Author : Hao Chen
// Date : 2014-07-19
/**********************************************************************************
*
* Sort a linked list using insertion sort.
*
**********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode *insertionSortList(ListNode *head) {
// zero or one element in list
if (head == NULL || head->next ==NULL){
return head;
}
ListNode *pSorted = NULL;
while ( head != NULL ){
/* remember the head */
ListNode *pHead = head;
/* trailing pointer for efficient splice */
ListNode **ppTrail = &pSorted;
/* pop head off list */
head = head->next;
/* splice head into sorted list at proper place */
while( *ppTrail!=NULL && pHead->val > (*ppTrail)->val ) {
ppTrail = &(*ppTrail)->next;
}
pHead->next = *ppTrail;
*ppTrail = pHead;
}
return pSorted;
}
void printList(ListNode* h)
{
while(h!=NULL){
printf("%d ", h->val);
h = h->next;
}
printf("\n");
}
ListNode* createList(int a[], int n)
{
ListNode *head=NULL, *p=NULL;
for(int i=0; i<n; i++){
if (head == NULL){
head = p = new ListNode(a[i]);
}else{
p->next = new ListNode(a[i]);
p = p->next;
}
}
return head;
}
int main(int argc, char** argv)
{
int n = 10;
if (argc>1){
n = atoi(argv[1]);
}
srand(time(NULL));
int *a = new int[n];
for(int i=0; i<n; i++){
a[i] = random()%n + 1;
}
ListNode *p = createList(a, n);
printList(p);
printList(insertionSortList(p));
delete[] a;
}