链表创建与打印(学生学号姓名)学生结构体

  1. 定义一个结构体
  2. 结构体内有一个指针向next(下一个链表的指针)
  3. 创建链表。
  4. 用sizeof函数测量结构体长度
  5. 先申请一个结构体长度的动态空间输入链表头部结构体数据
  6. 循环申请空间并输入结构体数据
  7. 把申请得空间用free函数释放
  8. 打印链表。
  9. 把指针指向链表头部,不断指向next,直到next为空
#include<stdio.h>
#include<stdlib.h>
#define len sizeof(stu)
typedef struct student{
    int num;
    char name[10];
    struct student *next;
}stu;
stu *creat_link()
{
    stu *head = NULL,*p,*p1;
    p = (stu *)malloc(len);
    printf("输入学号姓名:\n");
    scanf("%d%s",&p -> num,p -> name);
        while(p -> num != 0){
        if(head == NULL){
            head = p;
            p1 = p;
            p -> next = NULL;
        }
        else{
            p1 -> next = p;
            p1 = p;
        }
        p = (stu *)malloc(len);
        printf("输入学号姓名:\n");
        scanf("%d%s",&p -> num,p -> name);
    }
    free(p);
    return head;
}
void print(stu *head)
{
    stu *p;
    p = head;
    while(p != NULL){
        printf("%10d%10s\n",p -> num,p -> name);
        p = p -> next;
    }
}
int main()
{
    stu *head1;
    head1 = creat_link();
    print(head1);
    return 0;
}
  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
要构造结构体链表,首先需要定义结构体的内容,包括学号姓名和成绩。 ```c #include <stdio.h> #include <stdlib.h> // 定义结构体 typedef struct student { int id; char name[20]; int score; struct student* next; } Student; int main() { int n; printf("请输入学生人数: "); scanf("%d", &n); Student* head = NULL; Student* tail = NULL; // 输入学生信息并构造链表 for (int i = 0; i < n; i++) { printf("\n请输入第%d个学生学号: ", i+1); int id; scanf("%d", &id); printf("请输入姓名: "); char name[20]; scanf("%s", name); printf("请输入成绩: "); int score; scanf("%d", &score); // 创建新的学生结点 Student* newStudent = (Student*)malloc(sizeof(Student)); newStudent->id = id; strcpy(newStudent->name, name); newStudent->score = score; newStudent->next = NULL; // 将新的学生结点加入链表 if (head == NULL) { head = newStudent; tail = newStudent; } else { tail->next = newStudent; tail = tail->next; } } // 遍历链表打印学生信息 printf("\n学生信息如下:\n"); Student* current = head; while (current != NULL) { printf("学号: %d\n", current->id); printf("姓名: %s\n", current->name); printf("成绩: %d\n", current->score); printf("\n"); current = current->next; } // 释放链表内存 while (head != NULL) { Student* temp = head; head = head->next; free(temp); } return 0; } ``` 以上是一个通过输入学生信息构造结构体链表的程序。首先输入学生人数,然后按照提示输入每个学生学号姓名和成绩。程序将会创建新的学生结点,并通过将结点链接在一起构造链表。最后,程序将会遍历链表打印每个学生学号姓名和成绩。最后释放链表内存,结束程序的执行。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值