• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

wchenfeng

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

编写一个链表结构,读取任意多个用户输入。之后遍历链表,再将链表数据打印出来。

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h> //malloc free等函数会使用到这头文件

//定义链表的节点
typedef struct node_s {
    long num; //学号
    float score; //成绩
    struct node_s* next; //指向链表下一个节点的指针
} node_t; 
//node_t是typedef定义出来的节点类型

//n用来统计链表的长度
int n;

//创建一个包含学生信息的链表
node_t* create()
{     node_t *head, *p1, *p2;
	
	n = 0;
    p1 = p2 = (node_t*) malloc(sizeof(node_t));
	scanf("%ld %f", &p1->num, &p1->score);
    head = NULL;

    while (p1->num != 0) {
        n++;
        if (n == 1)
            head = p1;
        else
            p2->next = p1;
        p2 = p1;
        p1 = (node_t*) malloc(sizeof(node_t));
        scanf("%ld %f", &p1->num, &p1->score);
    }
    p2->next = NULL;
    return (head);
}

//遍历链表,打印节点内容
void print(node_t *head)
{
    node_t *p;  //如果链表为空,则不用访问了,直接返回
    if (head == NULL) {
        return;
    }  //p初始化为head指向的链表首元素
    for (p = head; p != NULL; p = p->next) {  //如果p指向的不是空指针,则访问它的数据
        printf("%ld %5.1f\n", p->num, p->score);  //访问完数据后,p要指向当前元素的下一个元素 p = p->next
    }  //如果p指向的是空指针,则跳出循环
}



//输出
void test_14_1(void)
{
    node_t* head;
 
    head = create();
    print(head);

}
int main(void)
{
    test_14_1();
}  

输入

2017001 81.0
2017002 82.0
2017003 83.0
2017004 84.0
2017005 85.0
2017010 90.0
0 0
 

输出

2017001  81.0
2017002  82.0
2017003  83.0
2017004  84.0
2017005  85.0
2017010  90.0

posted on 2022-04-12 20:03  王陈锋  阅读(46)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3