【发布时间】:2020-06-01 11:31:21
【问题描述】:
我正在尝试实现链表遍历,但是我的代码不起作用,我不明白为什么我重新分配了我的指针但它没有粘住?
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
void inserter(Node *n1, int num){
if(n1==NULL){
Node *temp =(Node*)malloc(sizeof(Node));
temp->data=num;
temp->next=NULL;
n1=temp;
}
else{
Node *trav=n1;
while(trav!=NULL){
trav=trav->next;
}
}
}
int main(int argc, char **argv)
{
Node *l1 = NULL;
inserter(l1,l2,5);
inserter(l1,l2,11);
//It goes back into the NULL bracket despite me assigning it a node?
}
这是附带的结构
typedef anode {
struct Node *next;
int data;
}Node;
感谢您的帮助!我还是新手。
【问题讨论】:
-
问题从分配
n1=temp开始。您不能分配给局部参数变量,因为它就像任何其他局部变量一样(除了它一开始是用一个值初始化的)。我建议你要么返回n1,要么研究在C 中通过引用模拟传递。 -
在其他情况下,一旦找到正确的位置,您就不会分配新节点
-
指针
n1是按值传递给您的函数的,因此您不能以这种方式将新值传回。您还使用 2 个参数声明了inserter函数,但您尝试传递三个参数,并且使用了l2,但未在main中定义。所以你展示的代码应该有编译错误。
标签: c data-structures linked-list