1 //动态链表插值
2 #include <stdio.h>
3 #include <stdlib.h>
4 #include <time.h>
5 typedef int datatype;
6 typedef struct node
7 {
8 datatype data;
9 struct node *next;
10 }linklist;
11 linklist *Creat();
12 void Insert(linklist *head,datatype x);
13 void Showlist(linklist *head);
14 void main()
15 {
16 linklist *head;
17 datatype x;
18 head = Creat();
19 Showlist(head);
20 printf("/n请输入要插入的数:/n");
21 scanf("%d",&x);
22 Insert(head,x);
23 Showlist(head);
24 free(head);
25 }
26 //创建链表
27 linklist *Creat()
28 {
29 srand( (unsigned)time( NULL ) );
30 int i = rand() % 5;
31 int j = 0;
32 linklist *head = (linklist *)malloc(sizeof(linklist));
33 if (head == NULL)
34 {
35 printf("内存分配出错!/n");
36 return NULL;
37 }
38 linklist *s = NULL;
39 linklist *r = head;
40 printf("请输入线性表的元素数:");
41 scanf("%d", &j);
42 if (j <= 0)
43 {
44 printf("不合法,将退出!/n");
45 return NULL;
46 }
47 for (; j > 0; j--)
48 {
49 s =(node*)malloc(sizeof(node));
50 if(s == NULL)
51 {
52 printf("内存分配出错!/n");
53 return NULL;
54 }
55 s->data = i += rand() % 5 + 1;
56 r->next = s;
57 r = s;
58 }
59 if (r != NULL)
60 {
61 r->next = NULL;
62 }
63 return head;
64 }
65 //插入函数
66 void Insert(linklist *head,datatype x)
67 {
68 linklist *s,*t;
69 s = (linklist *)malloc(sizeof(linklist));
70 s->data = x;
71 t = head;
72 while (t->next != NULL)
73 {
74 if (s->data > (t->next->data)&&s->data < (t->next->next->data))
75 {
76 s->next = t->next->next;
77 t->next->next = s;
78 return;
79 }
80 t = t->next;
81 }
82 if (t->next == NULL)
83 {
84 t->next = s;
85 s->next = NULL;
86 }
87 }
88 void Showlist(linklist *head)
89 {
90 linklist *temp = head->next;
91 while (temp != NULL)
92 {
93 printf("%d/t",temp->data);
94 temp = temp->next;
95 }
96 }