博客
关于我
使用C语言描述静态链表和动态链表
阅读量:68 次
发布时间:2019-02-26

本文共 1799 字,大约阅读时间需要 5 分钟。

静态链表和动态链表是线性表链式存储结构的两种不同的表示方式。静态链表的大小通常是固定的,这意味着所有结点都在程序中提前定义,并且不会因为插入或删除操作而改变大小。这种方法避免了内存动态分配带来的开销,只需通过指针进行链接操作即可完成任务。

与静态链表相比,动态链表的大小可以根据需要动态调整。这意味着动态链表可以灵活地增加或减少结点数量,而无需预先定义所有结点的位置。动态链表通常被认为是更通用的表示方法,尤其是在处理未知数据量或动态数据时。

静态链表的优点在于其空间效率较高,因为所有结点都在内存中预先分配,减少了内存分配和释放的开销。然而,这也限制了链表的大小,无法根据实际需求进行调整。而动态链表的劣势在于其空间利用率略低于静态链表,因为只有实际使用的结点会被分配内存。

在实际应用中,动态链表通常被用来处理数据量不确定或需要频繁插入删除操作的场景。例如,动态链表可以用来实现数据结构的扩展或收缩,适应不同数据量的需求。静态链表则更适合固定数据量或只需要简单操作的场景。

以下是两种链表的实现示例:

对于静态链表,所有结点都在程序中定义。以下是一个简单的C语言示例:

struct Student {    int num;    float score;    struct Student *next;};int main() {    struct Student stu1, stu2, stu3, *head, *p;    stu1.num = 1001;    stu1.score = 80;    stu2.num = 1002;    stu2.score = 85;    stu3.num = 1003;    stu3.score = 90;    head = &stu1;    stu1.next = &stu2;    stu2.next = &stu3;    stu3.next = NULL;    p = head;    do {        printf("%d,%f\n", p->num, p->score);        p = p->next;    } while (p != NULL);    system("pause");    return 0;}

对于动态链表,结点的分配和链接操作是在程序运行时完成的。以下是一个C语言的动态链表实现示例:

#include 
#include
struct Student { int No; struct Student *next;};int main() { struct Student *p1, *p2, *head; int n = 0; head = NULL; p1 = (struct Student *)malloc(sizeof(struct Student)); printf("请输入1个学号\n"); scanf("%d", &p1->No); p2 = p1; while (p1->No != 0) { n++; if (n == 1) { head = p1; } else { p2->next = p1; } p2 = p1; printf("请输入学号,输入0终止:\n"); p1 = (struct Student *)malloc(sizeof(struct Student)); scanf("%d", &p1->No); } p2->next = NULL; struct Student *p; p = head; while (p != NULL) { printf("%d,", p->No); p = p->next; } printf("\n"); system("pause"); return 0;}

总结来说,静态链表和动态链表各有优劣,选择哪一种取决于具体的应用场景和需求。

转载地址:http://chjz.baihongyu.com/

你可能感兴趣的文章
npm报错Failed at the node-sass@4.14.1 postinstall script
查看>>
npm报错fatal: Could not read from remote repository
查看>>
npm报错File to import not found or unreadable: @/assets/styles/global.scss.
查看>>
npm报错TypeError: this.getOptions is not a function
查看>>
npm报错unable to access ‘https://github.com/sohee-lee7/Squire.git/‘
查看>>
npm淘宝镜像过期npm ERR! request to https://registry.npm.taobao.org/vuex failed, reason: certificate has ex
查看>>
npm版本过高问题
查看>>
npm的“--force“和“--legacy-peer-deps“参数
查看>>
npm的安装和更新---npm工作笔记002
查看>>
npm的常用操作---npm工作笔记003
查看>>
npm的常用配置项---npm工作笔记004
查看>>
npm的问题:config global `--global`, `--local` are deprecated. Use `--location=global` instead 的解决办法
查看>>
npm编译报错You may need an additional loader to handle the result of these loaders
查看>>
npm设置淘宝镜像、升级等
查看>>
npm设置源地址,npm官方地址
查看>>
npm设置镜像如淘宝:http://npm.taobao.org/
查看>>
npm配置安装最新淘宝镜像,旧镜像会errror
查看>>
NPM酷库052:sax,按流解析XML
查看>>
npm错误 gyp错误 vs版本不对 msvs_version不兼容
查看>>
npm错误Error: Cannot find module ‘postcss-loader‘
查看>>