结构体指针实现动态链表

代码展示:

//结构体指针实现动态链表
#include<stdio.h>
#include<stdlib.h>
# define LEN sizeof(struct Student)
struct Student{
    int num;
    char name[20];
    float score;
    struct Student* next;
};
struct Student *p;

struct Student * creat()
{
    printf("创建动态链表......\n");
    struct Student *head,*p1,*p2;
    head=NULL;
    int n=0;
    p1=(struct Student*)malloc(LEN);
    scanf("%d%s%f",&p1->num,p1->name,&p1->score);
    while(p1->num!=0)
    {
        n+=1;
        if(n==1) head=p2=p1;
        else 
        {
            p2->next=p1;
            p2=p1;
        }
        p1=(struct Student*)malloc(LEN);
        scanf("%d%s%f",&p1->num,p1->name,&p1->score);
    }
    p2->next=NULL;
    free(p1);
    return head;
}

void print(struct Student*p)
{
    printf("链表如下:\n");
    if(p!=NULL)
    {
        do
        {
            printf("%-6d %-12s %6.2f\n",p->num,p->name,p->score);
            p=p->next;
        }while(p!=NULL);
    }
}

int main()
{
    p=creat();
    print(p);
    return 0;
}

 

运行结果:

 

posted @ 2020-03-17 23:06  kakusan  阅读(537)  评论(0编辑  收藏  举报