我创建了这个简单的双链表。问题是,当我打印其所有元素时,即使变量“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 指针。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句