我正在尝试创建一个程序,在其中输入“ + word”并添加单词,当您输入“ -word”时,它将单词从链接列表中删除。

插入单词对我来说很好,但是删除单词会导致分段错误。我不确定问题出在哪里。另外,有没有办法让您了解细分错误的位置?

void
remove_from_list(struct linked_list *list, char *data)
{
    struct node *current_node = list->head;
    struct node *previous_node = NULL;

    while (current_node != NULL) {
        if (current_node->data == data) {
            break;
        }
        previous_node = current_node;
        current_node = current_node->next;
    }
    if (previous_node == NULL) {
        list->head = list->head->next;
    } else {
        previous_node->next = current_node->next;
    }
    free(current_node);
    if (list->tail == current_node)
        list->tail = previous_node;
}

int
main(void)
{
    struct linked_list list = { .head = NULL, .tail = NULL };
    char word[50];

    do {
        printf("Enter string: ");
        fgets(word, 50, stdin);
        if (word[0] == '+')
            add_to_list(&list, word);
        else if (word[0] == '-')
            remove_from_list(&list, word);
    } while (word[0] != '\n');

    print_list_rec(&list);
    free_list(&list);
    return 0;
}

最佳答案

出现段错误的主要原因是因为您无法处理尝试删除时列表中没有数据的情况。

if (previous_node == NULL) {
    list->head = list->head->next;
} else { // ------------------------- If at the end of the list you go in here
    previous_node->next = current_node->next;
}


current_nodeNull,所以current_node->next seg错误。

之所以选择列表末尾,是因为您没有正确比较字符串的数据。像@this这样使用strcmp()来正确比较。但是,您应该处理列表中没有数据的情况。



您可以在while循环和第一个if语句之间添加检查,这将处理一个空列表和不在列表中的数据-

if(current_node == NULL) // Empty list or wasn't found
    return;




另一个注意事项:

您可以先释放current_node,然后再检查它是否为尾巴。颠倒此顺序。

if (list->tail == current_node)
    list->tail = previous_node;
free(current_node);

关于c - 从链接列表中删除项目时出现段错误,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24416909/

10-11 22:58
查看更多