ben*_*son 0 c structure linked-list
我想创建一个链接列表,我可以在以后添加更多元素,但我对当前代码的问题是所有以前的元素被最后添加的元素覆盖.这是我的代码:
#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;
}
Run Code Online (Sandbox Code Playgroud)
更改
int main()
{
char *str;
Run Code Online (Sandbox Code Playgroud)
至
int main()
{
char str[100]; // Or some other value to give scanf somewhere to put the data
Run Code Online (Sandbox Code Playgroud)
然后添加(假设您的设置可用此功能)
temp->name=strdup(str);
Run Code Online (Sandbox Code Playgroud)
我把释放记忆作为读者的练习
归档时间: |
|
查看次数: |
109 次 |
最近记录: |