我创建了这个简单的双链表。 问题是,当我打印它的所有元素时,即使变量“a”每次都发生变化,它们也具有相同的 char 值。
typedef struct node{
char *name;
struct node *n;
struct node *p;
} N;
N *h=NULL;//head
void insert(char *value){
N *temp=malloc(sizeof(N));
if(h==NULL){
h=temp;
temp->name=strdup(value);
}
else{
N *curr=h;
while(curr->n!=NULL)
curr=curr->n;
curr->n=temp;
temp->p=curr;
temp->name=strdup(value);
}
}
void print(){
N *temp=h;
printf("%s\n", temp->name);
while(temp->n!=NULL){
printf("%s\n", temp->name);
temp=temp->n;
}
}
int main(){
char a[...];
fgets(a,...)
//there is a while section: every time i enter in it, there is:
char *input=a;
insert(input);
print();
}
所以我期望的是: 狮子 熊 山羊 .... 相反,我得到: 那么狮子 熊 那么熊 山羊 山羊 山羊
等等...
最佳答案
有几个问题。首先, print() 中有一个错误,导致最后一个值无法显示。检查 temp 而不是 temp->n:
void print()
{
N *temp=h;
while(temp !=NULL){
printf("%s\n", temp->name);
temp=temp->n;
}
}
额外的 printf() 调用(在 while 循环之前)是第一个值被打印两次的原因。
此外,添加新节点时必须分配 p 和 n。如果您不分配它们,则不能假设它们将为 NULL。
void insert(char *value)
{
N *temp=malloc(sizeof(N));
if(h==NULL){
h=temp;
temp->p = NULL;
temp->n = NULL;
temp->name=strdup(value);
}
else{
N *curr=h;
while(curr->n!=NULL)
curr=curr->n;
curr->n=temp;
temp->p=curr;
temp->n = NULL;
temp->name=strdup(value);
}
}
另外,你需要列表是双链接的吗?您从不使用 p 指针。
关于c - 为什么我得到这个错误的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57747358/