C语言链表数据结构:创建、遍历和内存释放

代码示例:

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

struct student {
  int num;
  char name[20];
  double score;
  struct student *next;
};

int main() {
  struct student *a, *b, *c, *p, *head = NULL;

  a = (struct student *)malloc(sizeof(struct student));
  b = (struct student *)malloc(sizeof(struct student));
  c = (struct student *)malloc(sizeof(struct student));

  scanf("%d%s%lf", &a->num, a->name, &a->score);
  scanf("%d%s%lf", &b->num, b->name, &b->score);
  scanf("%d%s%lf", &c->num, c->name, &c->score);

  head = a;
  a->next = b;
  b->next = c;
  c->next = NULL;

  p = head;
  printf("%d,%s,%.2f\n", p->num, p->name, p->score);
  p = p->next;
  printf("%d,%s,%.2f\n", p->num, p->name, p->score);

  // 在程序结束前释放动态分配的内存
  free(a);
  free(b);
  free(c);

  return 0;
}

代码分析:

  • 创建链表节点: 使用 malloc() 函数为每个学生节点分配内存空间,并用 -> 运算符访问节点成员。
  • 建立链表: 将节点链接在一起,形成一个单向链表。
  • 遍历链表: 使用指针 p 遍历链表,访问每个节点的信息并打印。
  • 释放内存: 在程序结束前,使用 free() 函数释放每个节点的内存空间,避免内存泄漏。

总结:

本文展示了如何在 C 语言中创建和遍历单链表,并强调了释放内存的重要性。在使用 malloc() 动态分配内存后,必须使用 free() 函数释放内存,以防止内存泄漏,确保程序的稳定性。

C语言链表数据结构:创建、遍历和内存释放

原文地址: https://www.cveoy.top/t/topic/oikP 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录