我试图遍历链接列表,然后再向其中插入值。只是我试图插入唯一的值。请看一下我的代码。
当我在GCC编译器中运行代码时,出现了段错误
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct link
{
char name[14];
int data;
struct link *next;
}*start=NULL,*end=NULL,*tem=NULL;
void add(char nam[22])
{
struct link *temp;
temp=(struct link*)malloc(sizeof(struct link));
printf("Enter the data\n");
scanf("%d",&temp->data);
strcpy(temp->name,nam);
temp->next=NULL;
printf("\nadded\n");
if (start==NULL)
{
start=temp;
tem=start;
end=temp;
}
else
{
end->next=temp;
end=temp;
}
}
int traverse(char nam[22])
{
if(tem!=NULL){do
{
if(strcmp(tem->name,nam)==0)
{return 1;}
tem=tem->next;
}while(tem->next!=NULL);
}
return 0;
}
int main()
{
if(traverse("aaa")==0)
add("aaa");
else
printf("already present");
if(traverse("aaa")!=0)
printf("already present");
else
printf("not present ");//add("ashish");
if(traverse("bbb")!=0)
printf("already present");
else
printf("not present ");//add("bishnu");
return 0;
}
最佳答案
int traverse(char nam[22])
{
if(tem!=NULL){do
{
if(strcmp(tem->name,nam)==0)
{return 1;}
tem=tem->next;
}while(tem->next!=NULL);//this is error. You did not test tem==NULL after previos row
}
return 0;
}