craneX 发表于 2017-3-21 20:26:54

一个含有学生(学号,成绩的)单项动态链表问题,有一些地方看不懂,求解答,问题....

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

#define LEN sizeof(struct student)

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

struct student
{
      int num;
      float score;
      struct student *next;
};

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

void main()
{
      struct student *stu;

      stu = creat();//这里将create的返回值head赋值给stu
      print( stu );//不明白head的指向,为什么知道head的值就能进行打印?

      printf("\n\n");
      system("pause");
}

struct student *creat()
{
      struct student *head;
      struct student *p1, *p2;

      p1 = p2 = (struct student *)malloc(LEN);//这里的 (struct student *)malloc(LEN)是节点还是什么?

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

      head = NULL;   
      n = 0;   
      
      while( p1->num )
      {
            n++;
            if( 1 == n )
            {
                  head = p1;               
            }
            else
            {
                  p2->next = p1;
            }

            p2 = p1;
      p1 = (struct student *)malloc(LEN);//这里开辟的是新的节点还是什么,分配的len的长度又是多少,为什么要分配大小为sizeof(len>的内存。

            printf("\nPlease enter the num :");
            scanf("%d", &p1->num);//
            printf("Please enter the score :");
            scanf("%f", &p1->score);
      }

      p2->next = NULL;

      return head;
}

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

      p = head;
      if( head )
      {
            do
            {
                  printf("学号为 %d 的成绩是: %f\n", p->num, p->score);
                  p = p->next;//这里看不明白为什么这样可以直接指向下一个数据的节点。
            }while( p );
      }
}

language 发表于 2017-3-21 21:09:24

RE: 一个含有学生(学号,成绩的)单项动态链表问题,有一些地方看不懂,求解答,...

我根据你的问题一个个的来回答吧:
1.链表的构造一般是这样的:

每个节点都有一个next指针域,用来指向下一个节点,只要有一个头节点,可以通过这个节点的指针域找到下一个节点,然后通过循环遍历
2. malloc函数根据传入的值确定分配内存的大小,函数只是分配对应大小的内存,而不管分配的内存用来干什么,强制转化为这个节点类型,用来保存节点数据,一般都是分配节点大小的内存,这个只能多不能少,少了的话就保存不了这个数据。

craneX 发表于 2017-3-21 21:21:13

language 发表于 2017-3-21 21:09
我根据你的问题一个个的来回答吧:
1.链表的构造一般是这样的:



这里sizeof(struct student)具体大小是多少个字节,难道小一点(也就是小于int num;float score;      struct student *next;)在这个程序中就不行吗?

人造人 发表于 2017-3-21 21:38:04

craneX 发表于 2017-3-21 21:21
这里sizeof(struct student)具体大小是多少个字节,难道小一点(也就是小于int num;float score;   ...

可以看到是0ch(十进制12)

craneX 发表于 2017-3-21 22:23:23

人造人 发表于 2017-3-21 21:38
可以看到是0ch(十进制12)

谢谢,但是为什么这个节点需要12个字节的内存空间,p1,p2指向它的时候需要占用内存?

人造人 发表于 2017-3-21 22:27:55

craneX 发表于 2017-3-21 22:23
谢谢,但是为什么这个节点需要12个字节的内存空间,p1,p2指向它的时候需要占用内存?

struct student
{
      int num;
      float score;
      struct student *next;
};

一个 int 4个字节
一个 float 4个字节
一个   struct student *next4个字节

p1,p2指向它的时候只是指针变量本身占用内存
页: [1]
查看完整版本: 一个含有学生(学号,成绩的)单项动态链表问题,有一些地方看不懂,求解答,问题....