1,建立链表 #define NULL 0 #define LEN sizeof(struct stu) #include <stdio.h> #include <stdlib.h> struct stu { long num; float score; struct stu *next; }; int n; /*n记录链表长度*/ struct stu *creat(void) { struct stu *head,*p1,*p2; n=0; p1=p2=(struct stu*)malloc(LEN); scanf("%ld%f",&p1->num,&p1->score); head=NULL; /*这是链表为空时的情况*/ while(p1->num!=0) {n=n+1; if(n==1) head=p1; /*head指向新开辟的结点*/ else p2->next=p1; /*将新结点的地址赋给p2指向的上一个结点的next成员*/ p2=p1; /*改变p2,使它指向刚建立的结点*/ p1=(struct stu*)malloc(LEN); scanf("%ld%f",&p1->num,&p1->score); } p2->next=NULL; /*表尾结点指针域为空指针*/ return(head); } 可以在main()函数中调用creat函数。 2,输出链表 void print(struct stu *head) { struct stu *p; printf("/nThese %d records are:/n",n); p=head; if(head!=NULL) /*判断是否为空表*/ do { printf("%ld%5.1f/n",p->num,p->score); p=p->next; }while(p!=NULL); } 3,删除结点 struct stu*del(struct stu *head,long num) { struct stu *p1,*p2; if(head==NULL) {printf("/nlist null!/n");goto end;} p1=head; while(num!=p1->num&&p1->next!=NULL) { p2=p1; /*p2指向刚件查过的结点*/ p1=p1->next; } if(num==p1->num) /*如果找到了*/ { if(p1==head) /*如果要删除的是第一个结点*/ head=p1->next; /*调整头指针使指向第二个结点*/ else p2->next=p1->next; /*使p2不再指向p1,而指向p1的指向的下一个结点.p1所指向的结点不再是链表的元素*/ printf("delete:%ld/n",num); } else printf("%ld not found:/n",num); return(head); } 4,链表的插入 struct stu insert(struct stu *head,struct stu *stud) { struct stu *p0,*p1,*p2; p1=head; p0=stud; if(head==NULL) {head=p0;p0->next=NULL;} else while((p0->num>p1->num)&&(p1->next!=NULL)) /*寻找结点p1*/ {p2=p1; p1->p1->next; } if(p0->num<=p1->num) /*找到了*/ { if(head==p1) /*要插入位置为第一个结点之前*/ head=p0; p0->next=p1; else p2->next=p0; /*插入位置为中间某一结点p1之前*/ p0->next=p1; } else /*p0->num比所有结点的num都大,需放在表尾*/ {p1->next=p0; po->next=NULL; } n=n+1; return(head); }