Problem A: C语言习题 链表建立,插入,删除,输出

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
typedef struct student
 {
    long num;
    float score;
    struct student *next;
 }student;
 student *creatlink(void)
 {
     student *head = NULL;
     student *last , *p ;
     p =(student *)malloc(sizeof(student));
     scanf("%ld%f",&p->num,&p->score);
     while(p->num!=0)
     {
         if(head==NULL)
         {
             head=p;
         }
         else
             last->next=p;
         last=p;
         p =(student *)malloc(sizeof(student));
         scanf("%ld %f",&p->num,&p->score);
     }
     last->next=NULL;
     free(p);
     return head;
 }
student *dellink(student *head,long del)
 {
    student *p1=head,*p;
    while(p1)
    {
        if(del==p1->num)
        {
            p->next=p1->next;
            free(p1);
            break;
        }
        else
        {
            p=p1;
            p1=p1->next;
        }
    }
    return head;
 }
void printlink(struct student *head)
{
    while(head!=NULL)
    {
        printf("%ld %.2f\n",head->num,head->score);
        head=head->next;
    }
}
void freelink(struct student *head)
{
    student *p1=head;
    student *p;
    while(p1)
    {
        p=p1->next;
        free(p1);
        p1=p;
    }
}
student *insertlink(student *head,student *stu)
 {
     student *p=head;
     student *pe;
     student *last=NULL;
     student *newbase=(student *)malloc(sizeof(student));
     newbase->num=stu->num;
     newbase->score=stu->score;
     newbase->next=NULL;
     if(newbase==NULL)
        exit(-1);
     while(p->next!=NULL)
     {
         p=p->next;
     }
     last=p;
     p=head;
     if(newbase->num<head->num)
     {
         newbase->next=head;
         head=newbase;
     }
     else if(head->num<newbase->num&&newbase->num<last->num)
     {
         while((p->num<=newbase->num)&&(p->next!=NULL))
         {
             pe=p;
             p=p->next;
         }
         newbase->next=p;
         pe->next=newbase;
     }
     else
        last->next=newbase;
     return head;
 }

int main()

{

    struct student *creatlink(void);

    struct student *dellink(struct student *,long);

    struct student *insertlink(struct student *,struct student *);

    void printlink(struct student *);

    void freelink(struct student *);

    struct student *head,stu;

    long del_num;

    head=creatlink();

    scanf("%ld",&del_num);

    head=dellink(head,del_num);

    scanf("%ld%f",&stu.num,&stu.score);

    head=insertlink(head,&stu);

    scanf("%ld%f",&stu.num,&stu.score);

    head=insertlink(head,&stu);

    printlink(head);

    freelink(head);

    return 0;

}

  

猜你喜欢

转载自www.cnblogs.com/mjn1/p/9004812.html