蔡子经数据结构3.2

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



#include <time.h>
#include <stdlib.h>
#define MAXN 100
int a[MAXN];
int top = 0;
typedef struct
{
int val;
struct * next;
} node;

node* createNode()
{
node* ret = (node*)malloc(sizeof(node));
ret->next = NULL;
ret->val = -1;
return ret;
}

void Insert(node* pre, node* p, int x)
{
while(p)
{
if(x < p->val)
break;
pre = pre->next;
p = p->next;
}
node *in = createNode();
in->val = x;
in->next = p;
pre->next = in;
}

int cmp(const void* a, const void* b)
{
return *(int*)a - *(int*)b;
}

int main()
{
srand(time(NULL));
node* head = createNode();

for(int i = 0; i < 10; ++i)
{
a[top++] = rand()%100;
printf("%d ",a[top-1]);
}
puts("");
for(int i = 0; i < top; ++i)
Insert(head, head->next, a[i]);
node *p = head->next;
while(p)
{
printf("%d ",p->val);
p = p->next;
}
puts("");
qsort(a,top,sizeof(int),cmp);
for(int i = 0; i < top; ++i)
printf("%d ",a[i]);
return 0;
}