#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(void) /*创建链表*/ { struct student *head; struct student *p1,*p2; n=0; p1=p2=(struct student*)malloc(LEN);/*开辟一个新单元*/ scanf("%1d,%f",&p1->num,&p1->score); head=NULL; while(p1->num!=0) { n=n+1; if(n==1) { head=p1; } else { p2->next=p1; } p2=p1; p1=(struct student*)malloc(LEN); scanf("%1d,%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) do { printf("%1d %5.1f\n",p->num,p->score); p=p->next; } while (p!=NULL); } struct student *del(struct student *head,long num) /*链表的删除操作*/ { struct student *p1,*p2; if(head==NULL) { printf("\nlist is null! \n"); return NULL; } p1=head; while(num!=p1->num && p1->next!=NULL) { p2=p1; p1=p1->next; } if(num==p1->num) { if(p1==head) { head=p1->next; } else { p2->next=p1->next; } printf("delete:%1d\n",num); n=n-1; } else { printf("%1d not been found! \n",num); } return head; } struct student * insert(struct student *head,struct student *stud) /*链表的插入*/ { struct student *p0,*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; } else { p2->next=p0; } p0->next=p1; } else//插到链表尾 { p1->next=p0; p1->next=NULL; } n=n+1; return head; } } } void main() { struct student *head,*stu;//stu long del_num; printf("input records:\n"); head=creat(); print(head); printf("\ninput the deleted number:"); scanf("%1d",&del_num); /*head=del(head,del_num); print(head); printf("\ninput the inserted record:"); scanf("%1d,%f",&stu.num,&stu.score); head=insert(head,&stu); print(head);*/ while(del_num != 0) { head=del(head,del_num); print(head); printf("input the deleted number:"); scanf("%1d",&del_num); } printf("\ninput the inserted record:"); stu=(struct student *)malloc(LEN); scanf("%1d,%f",&stu->num,&stu->score); while(stu->num!=0) { head=insert(head,stu); print(head); printf("input the inserted record:"); stu=(struct student*)malloc(LEN); scanf("%1d,%f",&stu->num,&stu->score); } }
浙公网安备 33010602011771号