建立学生成绩单向链表

  • Post author:
  • Post category:其他



要求:

1、编写函数将输入的学生成绩组织成单向链表,学生信息包括学号、姓名、成绩;

2、当输入0时函数结束运行;

3、函数返回值返回函数运行状态;

4、创建的学生成绩链表采用引用参数返回。

(用到C++中的引用)

#include<stdio.h>
#include<stdlib.h>

typedef struct LNode{
    int id;
    char name[8];
    int score;
    struct LNode *next;
}LNode;

bool List_TailInsert(LNode *&L);
void List_Print(LNode *L);

int main(){
    LNode *head=(LNode *)malloc(sizeof(LNode));
    if(List_TailInsert(head)){
        List_Print(head);
    }else{
        printf("Failed to create the linked list!");
    }
    return 0;
}

bool List_TailInsert(LNode *&L){                   //尾插法正向建立单链表(包含头结点)
    int id;
    LNode *p,*tail=L;                       //声明头指针和尾指针
    printf("Enter student's id, name, score:\n");
    scanf("%d",&id);
    if(id==0){                              //若开始输入为0,则函数直接结束,返回NULL
        return false;
    }else{
        while(id!=0){                       //输入0时,函数结束
            p=(LNode *)malloc(sizeof(LNode));//为新结点申请内存空间
            p->id=id;                       //将读取到的数据存放到新结点
            scanf("%s%d",p->name,&p->score);
            p->next=NULL;
            tail->next=p;                   //链接上新结点
            tail=p;                         //尾结点指向新结点
            scanf("%d",&id);
        }
        tail->next=NULL;                    //数据输入完毕,尾节点置空
    	return true;    
    }
}

void List_Print(LNode *L){                  //打印链表中的所有数据
    printf("Student's id, name, score:\n");
    L=L->next;
    while(L){
        printf("%d %s %d\n",L->id,L->name,L->score);
        L=L->next;
    }
}


运行结果:


在这里插入图片描述

注:因为C语言中无引用,所以纯C的编译环境会报错;C++中增加了引用,用C++的编译环境可正常运行。



版权声明:本文为myec_lipse原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。