【问题标题】:Why Linked lists are created using structure pointers not structure variables? [duplicate]为什么使用结构指针而不是结构变量创建链接列表? [复制]
【发布时间】: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


【解决方案1】:

链接列表是“动态数据结构”之一,与任何类型的变量等静态数据结构相对。
主要优点(至少与“动态”属性相关的优点)是可以在运行时更改数据结构的总数。重点是结构,而不是结构内部的值。
对于您的问题,运行时最相关的变化是增加元素的数量,即添加更多元素,特别是添加一些在运行前无法预测的额外元素。 (我应该将运行时指定为程序已经忙于完成其工作的时间,即在设置变量之后。)
如果您使用变量(甚至是数组,甚至是最初创建后的可变长度数组),则该数字是固定的。您可以设置一个大数字,足以容纳最多所需的元素。但是,如果您无法确定这样的最大值,那么您就陷入了死胡同。

TLDR 动态数据结构可以在运行时增长(并且缩小并再次增长)。
变量不能。 所以我拒绝你的“使用结构变量也可以做到这一点”。

(此答案侧重于您已标记的 C。对于其他语言,包括 C++,必须讨论更多方面。)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2021-09-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-03
    • 1970-01-01
    相关资源
    最近更新 更多