C语言学习(29)

  1 //链表的学习
  2 #include<stdio.h>
  3 #include<malloc.h>
  4 #define LEN sizeof(struct student)
  5 struct student{
  6     int num;
  7     float score;
  8     struct student *next;
  9 };
 10 int n;//这个是链表节点的个数
 11 
 12 //创建链表
 13 struct student *create(){
 14     struct student *head,*p1,*p2;
 15     p1=p2=(struct student *)malloc(LEN);
 16     printf("请输入学生的号数和分数:\n");
 17     scanf("%d %f",&(p1->num),&(p1->score));
 18     while(p1->num!=0){//当输入的学生号数为0的时候结束循环
 19         n++;//节点数加1
 20         if(n==1){
 21             head=p1;
 22         }else{
 23             p2->next=p1;
 24         }
 25         p2=p1;
 26         p1=(struct student *)malloc(LEN);
 27         printf("请输入学生的号数和分数:\n");
 28         scanf("%d %f",&(p1->num),&(p1->score));
 29     }
 30     p2->next=NULL;
 31     free(p1);
 32     return head;
 33 }
 34 
 35 //输出链表
 36 void print(struct student *head){
 37     struct student *p;
 38     p=head;
 39     printf("\n下面是学生的信息:\n号数\t分数\n");
 40     while(p!=NULL){
 41         printf("%d\t%f\n",p->num,p->score);
 42         p=p->next;
 43     }
 44 }
 45 
 46 //删除链表
 47 struct student *del(struct student *head,int num){//num为要删除的学生的号数
 48     struct student *p1,*p2;
 49     p1=head;
 50     while(p1->num!=num && p1->next!=NULL){
 51         p2=p1;
 52         p1=p1->next;
 53     }
 54     //如果找到了这个号数
 55     if(p1->num==num){
 56         if(p1==head){//如果要删除的节点是首节点
 57             head=head->next;
 58         }else{
 59             p2->next=p1->next;
 60         }
 61         free(p1);
 62         printf("已经删除号数为%d的节点\n",num);
 63         n--;//节点数减1
 64     }else{
 65         printf("这个学生号数不存在\n");
 66     }
 67     return head;
 68 }
 69 
 70 
 71 //插入链表节点
 72 struct student *insert(struct student *head,struct student *stu){//第二个stu参数是要插入的新的链表节点
 73     struct student *p0,*p1,*p2;
 74     p1=head;
 75     p0=stu;
 76     if(head==NULL){//如果原本的链表就是为空,那么创建新的链表
 77         head=p0;
 78         p0->next=NULL;
 79     }else{
 80         while( (p0->num>p1->num) && (p1->next!=NULL) ){
 81             p2=p1;
 82             p1=p1->next;
 83         }
 84         if(p0->num <= p1->num ){
 85             if(head==p1){//p0是首节点
 86                 head=p0;
 87             }else{
 88                 p2->next=p0;//p0是中间的节点
 89             }
 90             p0->next=p1;//p0指向下一个节点
 91         }else{//p0是尾节点
 92             p1->next=p0;
 93             p0->next=NULL;
 94         }
 95     }
 96     n--;
 97     return head;
 98 }
 99 
100 
101 int main(){
102     struct student *head;
103     head=create();
104     print(head);
105     head=del(head,3);
106     print(head);
107     struct student *stu;
108     stu=(struct student *)malloc(LEN);
109     printf("请输入新添加的学生的号数和分数:\n");
110     scanf("%d %f",&stu->num,&stu->score);
111     head=insert(head,stu);
112     print(head);
113     return 0;
114 }

 

 

posted on 2018-06-28 11:38  孙悟空son_ku_kong  阅读(147)  评论(0编辑  收藏  举报

导航