//有头链表 #include <stdio.h> #include <string.h> #include <malloc.h> #define N sizeof(struct student) struct student { char name[20]; int num; int score; struct student * next; }; struct student * creat_list(int n); void print_list(struct student* head); void add_list(struct student* head); void delete_list(struct student* head); void sort_list(struct student* head); int main (void) { struct student * Head; int n; scanf("%d",&n); //输入你需要创建链表的长度 Head=creat_list(n);//返回头结点的地址 创建链表 print_list(Head); //发送头节点的地址 输出链表 add_list(Head); //发送头节点的地址 插入 delete_list(Head); //发送头节点的地址 删除 sort_list(Head); //发送头节点的地址 链表排序(这里是升序) print_list(Head); //发送头节点的地址 再次输出 return 0; } struct student * creat_list(int n) { int i=1; struct student *head,*p0,*p1; head=p0=(struct student* )malloc(N);//动态创建一块内存记为头结点 p1=(struct student* )malloc(N);//动态创建一块内存记为首结点; scanf("%d %s %d",&p1->num,p1->name,&p1->score); while(i<n) { p0->next=NULL; p1->next=p0->next; p0->next=p1; p0=p1; p1=(struct student * )malloc(N); scanf("%d %s %d",&p1->num,p1->name,&p1->score); i++; } p0->next=p1; p1->next=NULL; return head; } void print_list(struct student* head) { struct student *p0; p0=head->next; while(p0!=NULL) { printf("%s %d %d\n",p0->name,p0->num,p0->score); p0=p0->next; } } void add_list(struct student* head) { struct student*p0,*p1=head; p0=(struct student* )malloc(N); scanf("%d %s %d",&p0->num,p0->name,&p0->score); head=head->next; while(head!=NULL) { if(head->num>p0->num)//插在链表的头结点后边或中间 { p0->next=p1->next; p1->next=p0; break; } p1=head; head=head->next; } if(head==NULL)//插在链表的最后 { head->next=p0; p0->next=NULL; } } void delete_list(struct student* head) { struct student *p1=head; int num; scanf("%d",&num); head=head->next; while(head!=NULL) { if(head->num==num) { p1->next=head->next; free(head); break; } p1=head; head=head->next; } if(head==NULL) { p1->next=NULL; free(head); } } void sort_list(struct student* head) { struct student *p0,*p1,*p2; char a[10]; int m,n; for(p0=head->next;p0!=NULL;p0=p0->next) { p2=p0; for(p1=p0->next;p1!=NULL;p1=p1->next) { if(p2->num>p1->num)//升序排序 { p2=p1; } } if(p2!=p0) { m=p0->num; p0->num=p2->num; p2->num=m; strcpy(a,p0->name); strcpy(p0->name,p2->name); strcpy(p2->name,a); n=p0->score; p0->score=p2->score; p2->score=n; } } }