我的计算机成长之路-----链表具体的操作

              对动态单向链表进行建立、输出、查找、插入、删除、及释放操作

1 #include<stdio.h>
2 #include<stdlib.h>
3  //建立动态单向链表,结点类型;
4 typedef struct student{
5 int no;
6 int score;
7 struct student *next;
8 };
9 //创建一个链表
10 struct student *head;
11 struct student *creat()
12 {
13 struct student *p,*q;
14 int n, i;
15 printf("how many :");
16 scanf("%d",&n);
17 for(i=0;i<n;i++)
18 {
19 p=(struct student*)malloc(sizeof(struct student));
20 printf("NO :"); scanf("%d",&p->no);
21 printf("Score :"); scanf("%d",&p->score);
22 if(i==0) head = p;
23 else q->next=p;
24 q=p;
25 }
26 p->next=NULL;
27 return (head);
28 }
29 //输出由表头指针head指向的链表
30 void print(struct student *head)
31 {
32 struct student *p;
33 p=head;
34 while(p!=NULL)
35 {
36 printf("%d %d\n",p->no,p->score);
37 p=p->next;
38 }
39 }
40 //函数find由表头指针head指向链表中查找学号等于n的结点
41 void find(struct student *head)
42 {
43 int n;
44 struct student *p;
45 printf("enter NO :");
46 scanf("%d",&n);
47 p=head;
48 while(p!=NULL && p->no!=n)
49 p=p->next;
50 if(p!=NULL) printf("%d %d \n",p->no,p->score);
51 else printf(" not find %d student\n",n);
52 }
53 //以下函数insert用于有表头指针head指向链表中的第i个结点之后插入一个结点p
54 struct student *insert(struct student *head)
55 {
56 int i,j;
57 struct student *p,*q;
58 printf("第 i 个结点 :");
59 scanf("%d",&i);
60 p=(struct student*)malloc(sizeof(struct student));// fenpeiyigekongjian gei p 指针
61 printf("NO :"); scanf("%d",&p->no);//
62 printf("Score :"); scanf("%d",&p->score);//建了个新结点
63 if(i==0)
64 {
65 p->next=head;
66 head=p;
67 }
68 else
69 {
70 q=head;
71 for(j=1;j<i;j++) q=q->next;//找到第i个结点,让q指向
72 if(q!=NULL)
73 {
74 p->next=q->next;
75 q->next=p;
76 }
77 else printf("i too biger\n");
78 }
79 return (head);
80 }
81 //以下delete函数用于表头指针head指向的链表中删除第 i个结点
82 struct student *delet(struct student *head)
83 {
84 int i,j;
85 struct student *p,*q;
86 printf("enter i (i>0) :");
87 scanf("%d",&i);
88 if(i==1)
89 {
90 p=head;
91 head=head->next;
92 free(p);
93 }
94 else
95 {
96 q=head;
97 for(j=1;j<i-1;j++) q=q->next;
98 if(q!=NULL)
99 {
100 p=q->next;
101 q->next=p->next;
102 free(p);
103 }
104 else printf("i too biger\n");
105 }
106 return (head);
107 }
108 //以下由flist函数释放有表头head指向的链表
109 void flist(struct student *head)
110 {
111 struct student *p;
112 while(head !=NULL)
113 {
114 p=head;
115 head=head->next;
116 free(p);
117 }
118 printf("nothing\n");
119 }
120 int main()
121 {
122 struct student *head;
123 head=creat();
124 print(head);
125 find(head);
126 head=insert(head);
127 print(head);
128 head=delet(head);
129 print(head);
130 flist(head);
131
132 system("pause");
133 }
posted @ 2011-05-22 00:15  左手心_疼  阅读(379)  评论(1编辑  收藏  举报