-
Notifications
You must be signed in to change notification settings - Fork 0
/
294.c
128 lines (112 loc) · 2.44 KB
/
294.c
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
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
// http://www.bjfuacm.com/problem/294/
#include <stdio.h>
#include <stdlib.h>
struct LinkedList;
struct LinkedList {
struct LinkedList *next;
int val;
};
typedef struct LinkedList LinkedList;
typedef struct LinkedList *PtrToList;
typedef PtrToList List;
typedef PtrToList Position;
List CreateList(int );
List SelectionSort(List );
void PrintList(List );
void DestroyList(List );
Position GetNode(List * , Position );
int main()
{
int n;
while (1) {
scanf("%d", &n);
if (n == 0) break;
List L = CreateList(n);
L = SelectionSort(L);
PrintList(L);
DestroyList(L);
}
}
List CreateList(int n)
{
struct LinkedList dummy;
dummy.next = NULL;
Position p;
Position pre = &dummy;
while (n--) {
p = (PtrToList)calloc(1, sizeof(*p));
scanf("%d", &(p->val));
pre->next = p;
pre = p;
p->next = NULL;
}
return dummy.next;
}
List SelectionSort(List L)
{
struct LinkedList dummy;
dummy.next = NULL;
Position pre = &dummy;
Position p; // p for traversal and select min and insert to give up order
struct LinkedList min;
while (L != NULL) {
p = L;
min.next = L;
min.val = p->val;
while (p != NULL) {
if (min.val > p->val) {
min.next = p;
min.val = p->val;
}
p = p->next;
}
p = GetNode(&L, min.next);
pre->next = p;
p->next = NULL;
pre = p;
}
return dummy.next;
}
Position GetNode(List *L, Position p)
{
Position pre; // for choosing previous
Position l = (*L); // represent (*L)
struct LinkedList dummy;
dummy.next = l;
pre = &dummy;
while (pre->next != NULL) {
if (pre->next == p) {
if (pre == &dummy) {
(*L) = l->next;
}
pre->next = p->next;
return p;
} else {
pre = pre->next;
}
}
}
void PrintList(List L)
{
if (L == NULL) return;
Position p = L;
while (p != NULL) {
printf("%d%s", p->val, p->next == NULL? "\n": " ");
p = p->next;
}
}
void DestroyList(List L)
{
Position to_delete = L;
if (L->next == NULL) {
free(L);
} else {
Position p = L->next;
free(to_delete);
while (p != NULL) {
to_delete = p;
p = p->next;
free(to_delete);
}
}
}