C語言——鏈表,c語言
//鏈表的操作#include<stdio.h>#include<malloc.h>#define NULL 0 #define LEN sizeof(struct student)struct student{long num;float score;struct student *next;};//結點int n;//存放結點個數struct student *creat()//建立鏈表{struct student *head;//頭指標struct student *p1,*p2;n=0;head=NULL;p1=p2=(struct student*)malloc(LEN);//分配儲存空間printf("input num,score:\n");scanf("%ld,%f",&p1->num,&p1->score);while(p1->num!=0){n=n+1;if(n==1)//第一個結點head=p1;else{p2->next=p1;p2=p1;}p1=(struct student*)malloc(LEN);printf("input num&&score:\n");scanf("%ld,%f",&p1->num,&p1->score);}p2->next=NULL;return head;//返回頭指標}void print(struct student *head)//鏈表輸出{struct student*p;printf("\nNow,these %d records are:\n",n);p=head;if(head!=NULL)while(p!=NULL){printf("%ld\t%5.2f\n",p->num,p->score);p=p->next;}}struct student *del(struct student *head,long num)//鏈表的刪除操作{struct student *p1,*p2;if(head==NULL)//空鏈表{printf("\nListLink is null\n");goto end;}p1=head;while(num!=p1->num&&p1->next!=NULL)//尋找要刪除的結點,p1指向要刪除的結點,p2指向要刪除的結點的前一個結點{p2=p1;p1=p1->next;}if(num==p1->num){if(p1==head)//要刪除的結點是第一個結點head=p1->next;elsep2->next=p1->next;printf("delete %ld is succeed\n",num);n=n-1;}elseprintf("%ld not been found!\n",num);end:return head;}struct student *insert(struct student *head,struct student *stud)//鏈表的插入操作{struct student *p0,*p1,*p2;//p1存放插入位置的後一個結點,p2存放插入位置的前一個結點p1=head;p0=stud;//要插入的結點if(head==NULL)//若鏈表為空白鏈表{head=p0;p0->next=NULL;}else{while((p0->num>p1->num)&&(p1->next!=NULL))//尋找要插入的位置{p2=p1;p1=p1->next;}if(p0->num<=p1->num){if(head==p1)//插入位置為第一個結點,表頭head=p0;elsep2->next=p0;p0->next=p1;}else{p1->next=p0;//插入位置為表尾,p0->next=NULL;}}n=n+1;return head;}void main(){struct student *head,*stu;long del_num;printf("input records:\n");head=creat();//建立鏈表print(head);printf("\ninput the delete number:");scanf("%ld",&del_num);while(del_num!=0)//刪除結點{head=del(head,del_num);print(head);printf("\ninput the delete number:");scanf("%ld",&del_num);}printf("\ninput insert record:");stu=(struct student*)malloc(LEN);scanf("%ld,%f",&stu->num,&stu->score);while(stu->num!=0)//插入結點{head=insert(head,stu);print(head);printf("\ninput insert record:");stu=(struct student*)malloc(LEN);scanf("%ld,%f",&stu->num,&stu->score);}}