C语言回顾(6)

链表
链表是一种重要的数据结构,它是动态地进行存储分配的一种结构;当你存储数据时,必然会先定义一个固态数组长度用来存放数据,但有时你并不知道存储数据的大小,所以会尽可能的多分配固态数组的长度,防止出现无法存放完数据的现象,这就会使内存空间的过多分配,浪费内存空间;但如果使用链表,将不会出现这种情况,因为链表是用多少,就会分配多少内存,这样就防止了内存的浪费;链表是有结构体组成,每一个结构体相当于一个节点,而每一个节点都有它的数据域和指针域,数据域是存放数据的,而指针域是指向下一个节点的,第一个结构体名为头结点,而最后一个结构体为尾节点,其指针域指向NULL(空)。

静态链表
静态链表是在函数中就讲各个结构体相联系,在直接输出来:

#include<stdio.h>
#include<windows.h>
struct Student
{
 int num;
 int score;
 struct Student *next;
};
int main()
{
 struct Student a, b, c, *head, *p;
 a.num = 1001; a.score = 90;
 b.num = 1002; b.score = 92;
 c.num = 1003; c.score = 89;
 head = &a; a.next = &b; b.next = &c; c.next = NULL;
 p = head;
 do
 {
  printf("num=%d\n", p->num);
  printf("score=%d\n",p->score);
  p = p->next;
 } while (p != NULL);
 system("pause");
 return 0;
}

在这里插入图片描述
动态列表

动态链表是指程序在执行过程中,从无到有建立起的一个链表,一个个的开辟节点并存入数据,并建立起前后相连的关系。

#include<stdio.h>
#include<Windows.h>
#define LEN sizeof(struct Student)
struct Student
{
 long num;
 float score;
 struct Student*next;
};
int n;
struct Student *creat()
{
 struct Student *head, *p1, *p2;
 n = 0;
 p1 = p2 = (struct Student*)malloc(LEN);
 scanf_s("%ld,%f", &p1->num, &p1->score);
 head = NULL;
 while (p1->num != 0)
 {
  n = n + 1;
  if (n == 1)head = p1;
  else
   p2->next = p1;
  p2 = p1;
  p1 = (struct Student*)malloc(LEN);
  scanf_s("%ld,%f", &p1->num, &p1->score);
 }
 p2->next = NULL;
 return head;
}
void print(struct Student *head)
{
 struct Student*p;
 printf("\nNow,These%drecords are:\n", n);
 p = head;
 if (head != NULL)
  do
  {
   printf("%ld,%5.lf\n", p->num, p->score);
   p = p->next;
  } while (p != NULL);
}
int main()
{
 struct Student *head;
 head=creat();
 print(head);
 system("pause");
 return 0;
}

在这里插入图片描述
动态链表可以再调试后在往里面赋值。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值