【问题标题】:Issue inserting node in linked list问题在链表中插入节点
【发布时间】:2018-04-04 02:04:39
【问题描述】:

我正在练习创建链接列表,但在尝试将项目插入列表前面时遇到问题。如果我将插入函数中的代码放在 main 中,则插入函数中的代码可以正常工作,但作为函数单独运行时则不能。

我在函数中使用指针作为参数,所以我不明白为什么我的 print 语句中的值没有更改为 100,它应该使用插入函数位于链表的前面(当我运行函数打印61,我的目标是打印100)。

感谢您的帮助!

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

typedef struct node *nodePtr;
typedef struct node node;

struct node {
    int value;
    nodePtr next;
};


node insert(node *first, int value)
{
    nodePtr temp;
    temp = malloc(sizeof(node));
    temp->value = value;
    temp->next = first;
    first = temp;
}

int main()
{

    nodePtr first;
    first = malloc(sizeof(node));
    first->value = 61;
    first->next = NULL;
    insert(first, 100);

    printf("%d", first->value);
}

【问题讨论】:

  • 问题的意义为零。您的代码清楚地表明将打印 61。
  • 61 赋值,但期望100 输出,怎么能这样?
  • 我的错误,我不小心删除了应该在 first->next = NULL; 之下的 insert(first, 100) 行编辑代码时。我也会在主帖中更改它

标签: c data-structures linked-list


【解决方案1】:

您将指向节点的指针作为参数传递给函数并更改形式参数的值不会更改实际参数的值,这样做应该可以。

enter code here



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

   typedef struct node *nodePtr;
   typedef struct node node;

  struct node {
  int value;
  nodePtr next;
   };


 void insert(node **first, int value)
 {
 nodePtr temp;
 temp = malloc(sizeof(node));
 temp->value = value;
 temp->next = *first;
 *first = temp;
  }

 int main()
 {

nodePtr first;
first = malloc(sizeof(node));
first->value = 61;
first->next = NULL;
insert(&first, 100);
printf("%d",first->value);
}

【讨论】:

  • 我刚试了一下,似乎存储的值最终是一些随机长数字。知道为什么会这样吗?
  • 我发现了我的错误,我在插入函数中是先传入而不是 &first。谢谢!
【解决方案2】:

你已经传递了一个指向函数 insert() 的指针并将它存储在一个变量 first 中,该变量的作用域是函数 insert() 的局部变量.现在你有 更新了函数 insert() 中的指针 first

当您返回 main() 函数时,指针 next 的更新值丢失,这就是您在 main() 中打印值时得到意外结果的原因。

总结一下:

first = malloc(sizeof(node)); // let's say first is p1
...
insert(first, 100); // first is P1
....

node insert(node *first, int value) // first is p1
....
tmp = malloc(sizeof(node)); // let's say tmp is p2
first = temp; // Now first has become p2 but its scope is local to insert()

....
printf("%d", first->value); // first is still p1 here

解决方案

node* insert(node *first, int value)
{
    nodePtr temp;
    temp = malloc(sizeof(node));
    temp->value = value;
    temp->next = first;
    first = temp;
    return first;
}

int main()
{

    nodePtr first;
    first = malloc(sizeof(node));
    first->value = 61;
    first->next = NULL;
    first = insert(first, 100);

    printf("%d", first->value);
    return 0;
}

【讨论】:

    猜你喜欢
    • 2018-07-28
    • 1970-01-01
    • 1970-01-01
    • 2020-03-07
    • 1970-01-01
    • 2014-10-07
    • 2018-04-19
    相关资源
    最近更新 更多