我做了一个简单的链接列表,我想在其中添加元素,以检查元素是否已经存在。
如果要添加的新元素已经存在,则该节点将不会插入列表中。
嗯,问题是在插入第二个元素时开始的; gdb说:
Program received signal SIGSEGV, Segmentation fault.
0x0000555555554bda in search (name=0x5555557576d0 "alfred")
at Scrivania/test.c:*line*
*line* while(strncmp(name,temp->name,strlen(name))!=0)
代码:
typedef struct node{
char *name;
struct node *n;
} N;
N *h = NULL;
void insert(char *name){
N *temp = malloc(sizeof(N));
if (h == NULL){
h=temp;
temp->n = NULL;
temp->name = strdup(name);
} else {
N *curr = h;
while (curr->n != NULL)
curr = curr->n;
curr->n = temp;
temp->name = strdup(name);
}
}
N *search(char *name) {
N *temp = h;
if (temp == NULL)
return NULL;
else{
while (strncmp(name, temp->name, strlen(name)) != 0)
temp=temp->n;
return temp;
}
}
int main() {
char *name = N * temp=search(name); //getting input
if (temp == NULL)
insert(name);
//these four lines sequence repeat for every input
}