c - 为什么使用结构指针而不是结构变量创建链接列表?
问题描述
下面是使用结构指针和结构变量创建的链表的单独代码。
// Here a linked list is created using structure pointers
#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node * ptr;
};
void traversal(struct Node * poin)
{
while(poin != NULL)
{
printf("%d, ", poin->data);
poin = poin->ptr;
}
}
int main()
{
struct Node * head = NULL; // Structure pointers
struct Node * second = NULL;
struct Node * third = NULL;
head = (struct Node *) malloc (sizeof(struct Node));
second = (struct Node *) malloc (sizeof(struct Node));
third = (struct Node *) malloc (sizeof(struct Node));
head->data = 5;
head->ptr = second;
second->data = 23;
second->ptr = third;
third->data = 839;
third->ptr = NULL;
traversal(&head);
return 0;
}
// Here the same linked list is created using structure variables
#include <stdio.h>
struct Node
{
int data;
struct Node * ptr;
};
// Pointer poin moves along different elements of a linked list
void traversal(struct Node * poin)
{
while(poin != NULL)
{
printf("%d, ", poin->data);
poin = poin->ptr;
}
}
int main()
{
struct Node head, second, third; // Structure variables
head.data = 5;
head.ptr = &second;
second.data = 23;
second.ptr = &third;
third.data = 839;
third.ptr = NULL;
traversal(&head);
return 0;
}
如果我们忽略动态内存分配,为什么链表是使用结构指针创建的,而使用结构变量也可以做到这一点?它仍然让我感到困惑。
解决方案
链接列表是“动态数据结构”之一,与任何类型的变量等静态数据结构相对。
主要优点(至少与“动态”属性相关的优点)是可以在运行时更改数据结构的总数。重点是结构,而不是结构内部的值。
对于您的问题,运行时最相关的变化是增加元素的数量,即添加更多元素,特别是添加一些在运行前无法预测的额外元素。(我应该将运行时指定为程序已经忙于完成其工作的时间,即在设置变量之后。)
如果您使用变量(甚至是数组,甚至是最初创建后的可变长度数组),则该数字是固定的。您可以设置一个大数字,足以容纳最多所需的元素。但如果你不能确定这样的最大值,你就陷入了死胡同。
TLDR 动态数据结构可以在运行时增长(缩小并再次增长)。
变量不能。所以我拒绝你的“使用结构变量也可以做到这一点”。
(此答案侧重于您已标记的 C。对于其他语言,包括 C++,必须讨论更多方面。)
推荐阅读
- javascript - double combineLatest 不发出更新
- angular - 推送通知,多个 Service Worker?适用于 Web/Android/IOS 和 Firebase 的 Angular Ionic 5 PWA
- unity3d - 具有 A* Pathfinding Unity 的 500 个代理的性能非常低
- javascript - React-tooltip 不显示在条件渲染上
- c# - 我想通过 StreamReader 从文本文件中读取数据,编辑特定字符串并将其写入文件中
- javascript - 如何将多嵌套元素包装在另一个多嵌套元素中
- javascript - Laravel 7 jQuery阻止提交按钮
- wpf - 从 WinForms 应用程序控制 WPF 进度条
- python - 我当前对残差块的实现是否正确?
- reactjs - React JSX 条件渲染中断下拉列表