【问题标题】:what is the difference in the following codes for Linked List in c ? How is the memory managed in both cases ?Are there any performance differences?c中链接列表的以下代码有什么区别?在这两种情况下如何管理内存?是否有任何性能差异?
【发布时间】:2021-09-27 14:45:20
【问题描述】:

我是 C 的新手。两种情况下是否有不同的内存管理,例如第一个将数据存储在堆栈中,而第二个将数据存储在堆中。在第一种情况下,是编译器分配的内存。哪个更好用?

第一密码

#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node* next;
};

void printLL(struct Node* head){
    printf("%d ", (*head).data);
    if((*head).next!=NULL){
        printLL((*head).next);
    }
}

int main()
{
    struct Node first, second, third;
    
    first.data = 9;
    first.next = &second;
    
    second.data = 3;
    second.next = &third;
    
    third.data = 7;
    third.next = NULL;
    
    printLL(&first);
    
    return 0;
}

第二个密码

#include <stdio.h>
#include <stdlib.h>

struct Node{
    int data;
    struct Node* next;
};

void printLL(struct Node* head){
    printf("%d ", (*head).data);
    if((*head).next!=NULL){
        printLL((*head).next);
    }
}

int main()
{
    struct Node* first;
    struct Node* second;
    struct Node* third;
    
    first = (struct Node*)malloc(sizeof(struct Node));
    second = (struct Node*)malloc(sizeof(struct Node));
    third = (struct Node*)malloc(sizeof(struct Node));
    
    first->data = 9;
    first->next = second;
    
    second->data = 3;
    second->next = third;
    
    third->data = 7;
    third->next = NULL;
    
    printLL(first);
    
    return 0;
}

如果有任何资源可以阅读,请发送链接

【问题讨论】:

  • 主要区别在于节点的lifetime。在第一种情况下,他们的生命周期在他们离开scope 时结束。在第二种情况下,它们的生命周期在您调用 free 时结束。
  • AFAIK;堆上的 malloc 内存中的堆栈上的普通变量和堆栈上的指针。我不知道哪个更快。

标签: c linked-list dsa


【解决方案1】:

您似乎错过了动态内存数据结构的全部要点,其中链表通常是最先教授的。
运气不好,你的两个 MRE ( [mre] ) 有效地隐藏了这个好处。

为了亲自查看差异,请尝试在这两种情况下将另一个节点添加到您的链接列表中。请注意,它不需要直接访问,如果您可以从上一个节点访问它就足够了(否则会阻止这个概念)。

然后再做 100 次。

有关“链接列表”的任何课程材料、教科书或教程中的概念和(人工)用例的详细信息。我特意在此不提供解决方案,因为能够顺利融入您的其他学习进度的详尽示例/练习对您更有用。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多