【问题标题】:different ways of adding node in linked list在链表中添加节点的不同方法
【发布时间】:2016-02-19 09:14:58
【问题描述】:

这个简单的代码(将元素添加到链表并打印出来)工作正常

#include <stdio.h>
struct node{
    int item;
    struct node* next;
};

void print_node (struct node* n){
    while (n!= NULL){
        printf("%d ", (*n).item);
        n = n->next;
    }
    printf("\n");
}

void append_node(struct node *list, struct node *n){

    while(list->next != NULL)
        list = list->next;

    list->next = n;

}

int main(){
    struct node n1, n2;
    n1.item = 1;
    n1.next = NULL;

    n2.item = 2;
    n2.next = NULL;

    print_node(&n1);
    print_node(&n2);

    append_node(&n1,&n2);

    print_node(&n1);

    printf("done\n");
    return 0;
}

如果我将 append_node 定义如下

void append_node(struct node *list, struct node n){

    while(list->next != NULL)
        list = list->next;

    list->next = &n;

}

并在主程序中相应地调用它(即 append_node(&amp;n1, n2) )运行程序时出现分段错误。我不明白为什么:)

【问题讨论】:

  • struct node n 是局部变量。在函数外部范围内无效。
  • 在这个标签中询问的 LL 问题中至少有一半具有相同的“本地变量”问题:(
  • Ops,对不起,可能我没有搜索正确的关键字...顺便说一句,这主要是 java 的错。 ;)

标签: c linked-list


【解决方案1】:

当您调用append_node(struct node *list, struct node n) 时,参数n 会复制到函数上下文中。

当函数离开时,上下文被释放,你的数据的副本n会丢失。

如果您在将n(使用malloc)复制到链接列表之前,则可以使用您的函数append_node(struct node *list, struct node n)

编辑

这可能会对您有所帮助:What's the difference between passing by reference vs. passing by value?

【讨论】:

  • 函数内的 n 的内容是否已从内存中删除,即使它已链接到列表?
  • 是的:在你的链表中,你只要把n的地址放在函数本地。你可以运行 add some printf("address of n is %p\n", &amp;n); 来可视化它。在这种情况下,您可能会注意到 malloc 生成的地址和堆栈地址不同。
  • 所有函数变量(参数)都存储在堆栈中,当函数返回时,它的所有变量都被销毁(无法访问,可能包含一些其他数据)。
  • 好的,那么(只是为了便于理解),我想修改函数 print_node 使其不接收指针。我设法写成这样(它有效): void print_node (struct node n){ while (1){ printf("%d ", n.item); if (n.next == NULL) 中断; n = *(n.next); } printf("\n");当 n 不是指针时,我怎么能在 while 中写 n!=NULL 之类的东西,以便不在循环内进行中断?
  • @Peter:如果你愿意,你可以这样做。只需确保在本地 struct node* n 中分配 next 节点指针并为其使用适当的 printf
猜你喜欢
  • 2022-01-07
  • 1970-01-01
  • 2010-09-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-10
  • 1970-01-01
相关资源
最近更新 更多