链表

来源:互联网 发布:网卡mac地址怎么恢复 编辑:程序博客网 时间:2024/06/06 12:54
#include<stdio.h>#include<malloc.h>struct stu{int num;char mz[20];float fs;struct stu *next;};  struct stu *cheat()//指针函数,返回值为为指针的函数  { struct stu *head;                                                                                                                                                              struct stu *p; struct stu *tail;//链表尾部  int x; head=tail=NULL; scanf("%d",&x); while(x!=0) { p=(struct stu *)malloc(sizeof(struct stu)); p->num=x; if(head==NULL) head=p; scanf("%s",&p->mz); scanf("%f",&p->fs);  if(tail!=NULL) tail->next=p; tail=p; scanf("%d",&x); } if(tail!=NULL) tail->next=NULL; return head; } void list(struct stu *head) { struct stu *p; p=head; if(head!=NULL) { printf("信息如下\n"); while(p!=NULL) { printf("%d\t%s\t%5.1f\n",p->num,p->mz,p->fs); p=p->next;  }  } else printf("输入错误\n"); } //中间插入2 3 5中插入4  struct stu *InsertMid(struct stu *head,int num,struct stu *node) { struct stu *p,*p2; p=head; if(head==NULL) { head=node; node->next=NULL; return head;}else{while(p->num<num&&p!=NULL){p2=p;p=p->next;}if(p!=NULL){if(head==p)head=p;elsenode->next=p;p2->next=node;}else{p2->next=p;p->next=NULL;}}return head; } //在学号为num后面插入  struct stu *InsertPar(struct stu *head,int num,struct stu *node) { struct stu *p; p=head; if(head==NULL) { head=node; head->next=NULL;  return head;}while(p->next!=NULL&&p->num!=num){p=p->next;} if(p->num==num) { node->next=p->next; p->next=node; } else printf("No find!\n"); return head;  }  main() { struct stu *head; head=cheat();//调用cj()函数,返回值赋给head  list(head); printf("\n");  struct stu *node; node=(struct stu *)malloc(sizeof(struct stu));  printf("请输入插入学生的信息\n"); scanf("%d%s%f",&node->num,&node->mz,&node->fs);  printf("请输入插入方式\n(1)中间插入\n(2)指定位置后插入\n"); int order;scanf("%d",&order);switch (order){case 1:{//中间插入 head=InsertMid(head,node->num,node);break;}case 2:{//指定位置后插入 head=InsertPar(head,node->num,node);break;} }  list(head);  }

原创粉丝点击