[英]Issue inserting node in linked list
我正在练习创建链接列表,但是尝试在列表的前面插入项目时遇到了问题。 如果将插入函数放入main中,则插入函数中的代码可以正常工作,但作为函数单独运行时,则不能。
我在函数中使用指针作为参数,所以我不明白为什么我的print语句中的值未更改为100,该值应该使用insert函数位于链接列表的最前面(当我运行函数时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);
}
您传递指向节点的指针作为函数的参数并更改形式参数的值不会更改实际参数的值,这样做应该可以。
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);
}
您已将指针传递给函数insert(),并将其首先存储在变量的范围内,该变量的作用域是函数insert()的局部范围。 现在,您首先在函数insert()中更新了指针。
当您返回main()函数时, 下一个指针的更新值将丢失,这就是为什么在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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.