【发布时间】:2021-01-07 07:17:39
【问题描述】:
以下是使用结构指针和结构变量创建的链表的单独代码。
// 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;
}
如果我们忽略动态内存分配,为什么链表是使用结构指针创建的,而使用结构变量也可以做到这一点?我仍然感到困惑。
【问题讨论】:
-
因为你不知道你需要多少开始 - 它是一个动态数据结构......你也不能创建一个函数的本地节点,因为在返回时,本地函数中的副本被破坏。如果在您的示例中,您知道需要 3 个节点,那么您实际上并没有一个列表,您有 3 个由指针链接的节点。
-
可以复制结构“变量”,但不复制而链接到结构“变量”的唯一方法是使用指针。
-
更不用说在自身内部嵌套结构是不可能的。
-
您也可以浏览这 2 个主题,以就该主题进行更多讨论。 [为什么我们在链接列表中声明指向同一个结构的指针](stackoverflow.com/q/32026292/7610724) 和Why the pointer in linked list is of structure type?
标签: c