【发布时间】: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