C语言数据结构——链表的创建

什么是链表?

链表是一种常见的重要的数据结构,是动态的能进行存储分配的一种结构
链表的组成:
头指针:存放一个地址,该地址指向第一个元素
结点:用户需要的实际数据和链接结点的的元素
C语言数据结构——链表的创建_第1张图片

接下来根据下图尝试创建一个链表
C语言数据结构——链表的创建_第2张图片

struct student{
    int num;
    float score;
    struct student *next;
};
int main(){
    struct student stu1,stu2,*head;
    stu1.num = 10101;
    stu1.score = 89.5;

    stu2.num = 10103;
    stu2.score  = 90.0;

    head = &stu1;
    stu1.next = &stu2;
    stu2.next = NULL;

    while (head) {
        printf("%d\n%5.1f\n", head->num, head->score);
        head = head->next;
    }
    return 0;
}

然后接下来我们来尝试建立一下动态链表

所谓动态链表是指,在程序执行过程中从无到有的建立起一个链表,即一个一个地开辟结点和输入各结点数据,并建立起前后相链的关系。

C语言数据结构——链表的创建_第3张图片

#include 
#include 
#include 

#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();//将链表头结点地址返回回来 
      print(stu);
      system("pause");
}

struct student *creat()//创建链表 
{
      struct student *head;//创建链表头结点 
      struct student *p1, *p2;//创建两个结构体指针 
  
      p1 = p2 = (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;    //总结点数为0 
      
      while( 0 != p1->num )//设置链表产生新元素的条件 
      {
            n++;
            if( 1 == n )
            {
                  head = p1;//如果原来链表为空,就把p1设置为头结点                 
            }
            else
            {
                  p2->next = p1;//如果原来链表中就有数据,就让新产生的所谓的p1,放到p2->next的位置 
            }

            p2 = p1;//整体往后挪一个单位 
            p1 = (struct student *)malloc(LEN);//先预分配内存,根据赋值结果进行具体处理 

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

      p2->next = NULL;//当跳出循环的话,就让p2->next画上一个句号,表示链表生成完毕 

      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 );
      }
}

C语言数据结构——链表的创建_第4张图片

你可能感兴趣的:(数据结构与算法,C语言)