鱼C论坛

 找回密码
 立即注册
查看: 3318|回复: 2

链表怎么这么难理解

[复制链接]
发表于 2019-8-9 15:45:20 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能^_^

您需要 登录 才可以下载或查看,没有账号?立即注册

x
本帖最后由 编程小土豆 于 2019-8-9 15:45 编辑

这段代码看了一天,还是有几个地方没搞懂,希望大家帮忙讲一下:
  1. #include <stdio.h>
  2. #include <malloc.h>
  3. #include <stdlib.h>

  4. #define LEN sizeof(struct student)

  5. struct student *creat();   //创建链表
  6. void print(struct student *head);   //打印链表

  7. struct student
  8. {
  9.       int num;
  10.       float score;
  11.       struct student *next;
  12. };

  13. int n; //全局变量,用来记录存放了多少数据。

  14. void main()
  15. {
  16.       struct student *stu;

  17.       stu = creat();
  18.       print( stu );

  19.       printf("\n\n");
  20.       system("pause");
  21. }

  22. struct student *creat()
  23. {
  24.       struct student *head;
  25.       struct student *p1, *p2;
  26.   
  27.       p1 = p2 = (struct student *)malloc(LEN);

  28.       printf("Please enter the num :");
  29.       scanf("%d", &p1->num);
  30.       printf("Please enter the score :");
  31.       scanf("%f", &p1->score);

  32.       head = NULL;     
  33.       n = 0;   
  34.       
  35.       while( p1->num )
  36.       {
  37.             n++;
  38.             if( 1 == n )
  39.             {
  40.                   head = p1;                 
  41.             }
  42.             else
  43.             {
  44.                   [color=Red]p2->next = p1[/color];
  45.             }

  46.             [color=Red]p2 = p1[/color];
  47.             p1 = (struct student *)malloc(LEN);

  48.             printf("\nPlease enter the num :");
  49.             scanf("%d", &p1->num);
  50.             printf("Please enter the score :");
  51.             scanf("%f", &p1->score);
  52.       }

  53.       p2->next = NULL;

  54.       return head;
  55. }

  56. void print(struct student *head)
  57. {
  58.       struct student *p;
  59.       printf("\nThere are %d records!\n\n", n);

  60.       p = head;
  61.       if( head )
  62.       {
  63.             do
  64.             {
  65.                   printf("学号为 %d 的成绩是: %f\n", p->num, p->score);
  66.                   p = p->next;
  67.             }while( p );
  68.       }
  69. }
复制代码

视频教程里写的是:“如果输入的p1->num=0,则应链入第二个结点(n=2),将新结点的地址赋给第一个结点的next成员。 接着使p2 = p1,也就是使p2指向刚才建立的结点”
标红的这两条,p1和p2到底哪个是新结点呀,谁是第一个,谁是第二个呢?
小甲鱼最新课程 -> https://ilovefishc.com
回复

使用道具 举报

 楼主| 发表于 2019-8-9 15:46:25 | 显示全部楼层
本帖最后由 编程小土豆 于 2019-8-9 15:47 编辑

在源代码里有“color”的两句话
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

发表于 2019-8-9 17:06:12 | 显示全部楼层
两个东西,一个是自己的,一个是下个数据的地址(方便寻找)
小甲鱼最新课程 -> https://ilovefishc.com
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

小黑屋|手机版|Archiver|鱼C工作室 ( 粤ICP备18085999号-1 | 粤公网安备 44051102000585号)

GMT+8, 2025-7-1 09:35

Powered by Discuz! X3.4

© 2001-2023 Discuz! Team.

快速回复 返回顶部 返回列表