你的位置:首页 > 信息动态 > 新闻中心
信息动态
联系我们

学习笔记 简单链表

2021/12/29 6:03:10

编程要求

输入若干学生的信息(学号、姓名、成绩),当输入学号为 0 时结束,用单向链表组织这些学生信息后,再按序输出。

代码实现

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
typedef struct stud_node
{
    int num;
    char name[20];
    int score;
    struct stud_node* next;
}List;

int size = sizeof(List);

int main()
{
    struct stud_node* head = NULL, * tail = NULL, * p = NULL;
    int num = 0, score = 0;
    char name[20] = { 0 };
    head = (List*)malloc(size);
    if (head == NULL)
    {
        //printf("%s", strerror(errno));
        return 0;
    }
    tail = head;
    printf("input num,name and score:\n");
    scanf("%d", &num);
    while (num != 0)
    {
        p = (List*)malloc(size);
        if (p == NULL)
        {
            return 0;
        }
        scanf("%s %d", name, &score);
        p->num = num;
        strcpy(p->name, name);
        p->score = score;
        p->next = NULL;
        tail->next = p;
        tail = p;
        scanf("%d", &num);
    }
    tail->next = NULL;
    for (p = head; p->next != NULL;)
    {
        p = p->next;
        printf("%d  %s  %d\n", p->num, p->name, p->score);
    }
    return 0;
}