博客
关于我
使用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/

你可能感兴趣的文章
NotImplementedError: Could not run torchvision::nms
查看>>
nova基于ubs机制扩展scheduler-filter
查看>>
Now trying to drop the old temporary tablespace, the session hangs.
查看>>
nowcoder—Beauty of Trees
查看>>
np.arange()和np.linspace()绘制logistic回归图像时得到不同的结果?
查看>>
np.power的使用
查看>>
NPM 2FA双重认证的设置方法
查看>>
npm build报错Cannot find module ‘webpack/lib/rules/BasicEffectRulePlugin‘解决方法
查看>>
npm build报错Cannot find module ‘webpack‘解决方法
查看>>
npm ERR! ERESOLVE could not resolve报错
查看>>
npm ERR! fatal: unable to connect to github.com:
查看>>
npm ERR! Unexpected end of JSON input while parsing near '...on":"0.10.3","direc to'
查看>>
npm ERR! Unexpected end of JSON input while parsing near ‘...“:“^1.2.0“,“vue-html-‘ npm ERR! A comp
查看>>
npm error Missing script: “server“npm errornpm error Did you mean this?npm error npm run serve
查看>>
npm error MSB3428: 未能加载 Visual C++ 组件“VCBuild.exe”。要解决此问题,1) 安装
查看>>
npm install CERT_HAS_EXPIRED解决方法
查看>>
npm install digital envelope routines::unsupported解决方法
查看>>
npm install 卡着不动的解决方法
查看>>
npm install 报错 EEXIST File exists 的解决方法
查看>>
npm install 报错 ERR_SOCKET_TIMEOUT 的解决方法
查看>>