对于下面的代码,我尝试使用null head和null tail实现双向链表的insert函数。由于某种原因,程序不断出现看似随机的seg错误,并且没有进入正确的 if 或 elseif 语句。这是有问题的代码和终端输出:
void Insert(struct list_s* list, char* val) {
struct list_node_s* temp_p;
struct list_node_s* curr_p = list->h_p;
struct list_node_s* prev_p = NULL;
temp_p = Allocate_node(sizeof(val));
temp_p->data = val;
while (curr_p != NULL){
if (strcmp(curr_p->data, val) > 0){
prev_p = curr_p;
curr_p = curr_p->next_p;
}
else if (strcmp(curr_p->data, val) < 0){
break;
}
else{
printf("Thats already in the list!\n");
break;
}
}
printf("while\n");
if (list->h_p == NULL){ //none are in list
printf("here1\n");
list->h_p = temp_p;
list->t_p = temp_p;
}
else if (curr_p->next_p == NULL){ //if end of list
printf("here2\n");
curr_p->next_p = temp_p;
temp_p->pred_p = curr_p;
list->t_p = temp_p;
}
else{
printf("here3\n");
temp_p->next_p = curr_p;
curr_p->pred_p = temp_p;
temp_p->pred_p = prev_p;
prev_p->next_p = temp_p;
}
Free_node(curr_p);
}
终端输出:
Stevens-MacBook-Air:CS220 Steven$ gcc -g -Wall -o linked_list_test linked_list_test.c
Stevens-MacBook-Air:CS220 Steven$ ./linked_list_test
Please enter a command (i, p, m, d, f, q): i
Please enter a value: h
while
here1
Please enter a command (i, p, m, d, f, q): i
Please enter a value: j
while
Segmentation fault: 11
Stevens-MacBook-Air:CS220 Steven$ ./linked_list_test
Please enter a command (i, p, m, d, f, q): i
Please enter a value: h
while
here1
Please enter a command (i, p, m, d, f, q): i
Please enter a value: j
while
Segmentation fault: 11
Stevens-MacBook-Air:CS220 Steven$ ./linked_list_test
Please enter a command (i, p, m, d, f, q): i
Please enter a value: b
while
here1
Please enter a command (i, p, m, d, f, q): i
Please enter a value: a
while
here2
Please enter a command (i, p, m, d, f, q): ^C
Stevens-MacBook-Air:CS220 Steven$ gcc -g -Wall -o linked_list_test linked_list_test.c
Stevens-MacBook-Air:CS220 Steven$ ./linked_list_test
Please enter a command (i, p, m, d, f, q): i
Please enter a value: b
while
here1
Please enter a command (i, p, m, d, f, q): i
Please enter a value: c
while
here2
Please enter a command (i, p, m, d, f, q): i
Please enter a value: d
while
here3
Segmentation fault: 11