我想创建一个链接列表,我可以在稍后添加更多元素,但是现在的代码中存在的问题是,所有以前的元素都被添加的最后一个元素覆盖。这里是我的代码:将元素添加到链接列表(C)
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node {
char *name;
struct node *next;
}*head;
void add(char *str) {
struct node *temp;
temp=(struct node *)malloc(sizeof(struct node));
temp->name=str;
if (head== NULL) {
head=temp;
head->next=NULL;
} else {
temp->next=head;
head=temp;
}
}
void display(struct node *r) {
r=head;
if(r==NULL)
return;
while(r!=NULL) {
printf("%s ",r->name);
r=r->next;
}
printf("\n");
}
int main()
{
char *str;
struct node *n;
head=NULL;
while(scanf("%s",str) == 1) {
add(str);
display(n);
}
return 0;
}
为什么没有在缩进代码更好的尝试?也许学习使用调试器是当天的顺序 –
函数'display'不需要'r'作为参数。尝试'void display(){struct node * r = head; ...}' – francis
我明白了!非常感谢你! – benson