gpt4 book ai didi

C:将唯一值放入单链表中

转载 作者:行者123 更新时间:2023-11-30 19:18:43 26 4
gpt4 key购买 nike

我试图在插入值之前遍历链接列表。我只是想插入唯一值。请看看我的代码。当我在 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;
}

关于C:将唯一值放入单链表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26438732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com