-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinsertion_sort_list.c
More file actions
101 lines (88 loc) · 1.7 KB
/
insertion_sort_list.c
File metadata and controls
101 lines (88 loc) · 1.7 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* =====================================================================================
*
* Filename: insertion_sort_list.c
*
* Description: Insertion Sort List.
*
* Version: 1.0
* Created: 2015/02/25 20时20分13秒
* Revision: none
* Compiler: gcc
*
* Author: Zhu Xianfeng <xianfeng.zhu@gmail.com>
* Organization:
*
* =====================================================================================
*/
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode *
insertionSortList(struct ListNode *head)
{
struct ListNode *iter = head;
struct ListNode *start;
struct ListNode *end;
int val;
if (!head) {
return NULL;
}
while (iter->next) {
start = head;
end = iter->next;
while (start != end) {
if (start->val > end->val) {
val = start->val;
start->val = end->val;
end->val = val;
}
start = start->next;
}
iter = iter->next;
}
return head;
}
void
generateList(struct ListNode **head, int *arr, int n)
{
struct ListNode *ptr = NULL;
struct ListNode *tmp;
int i;
for (i = 0; i < n; i++) {
tmp = calloc(1, sizeof(struct ListNode));
tmp->val = arr[i];
if (!ptr) {
ptr = tmp;
} else {
ptr->next = tmp;
ptr = tmp;
}
if (!*head) {
*head = tmp;
}
}
}
void printList(struct ListNode *head)
{
struct ListNode *ptr = head;
printf("List: ");
while (ptr) {
printf("%d ", ptr->val);
ptr = ptr->next;
}
printf("\n");
}
int main(int argc, char *argv[])
{
struct ListNode *head = NULL;
int arr[] = {5, 2, 3, 8, 1};
generateList(&head, arr, 5);
printList(head);
head = insertionSortList(head);
printList(head);
return 0;
}