C - 链接列表 - 删除节点

时间:2013-12-01 06:16:19

标签: c linked-list nodes

这假设删除包含数据“last”的所有节点,该数据与字符串“name”相同。它没有给我一个错误,但它没有正常工作。它删除的内容超过了删除所需的内容。

struct node* mydelete(struct node *head) {
    char name[21];
    struct node *temp;

    printf("---Please enter last name:");
    scanf("%s", &name);
    while (head->next != NULL) {
        if (strcmp(head->last,name) == 0) {
            temp = head;
            head = head->next;
            free(temp);
            n--;
        } else if (strcmp(head->next->last,name)==0) {
            temp = head->next;
            head->next = head->next->next;
            free(temp);
            n--;
        } else
            head = head->next;
    }

    return head;
}

3 个答案:

答案 0 :(得分:1)

return head

错了。当你向前移动头部(到“下一个”)时,它所经过的任何东西都会丢失 - 你可能不会释放它们中的一些,但你不能再得到它们了。您应该使用临时指针来保存列表中的第一个节点(删除后),并最后返回它。

并且,不要忘记head == NULL。



从您的代码修改:

struct node *first = NULL;
while(head != NULL)
{
    if(strcmp(head->last,name)==0)
    {   //delete head
        temp = head;
        head = head->next;
        free(temp);
        n--;
    }
    else
    {   //delete head->next

        if (first == NULL)
            first = head;

        if (head->next == NULL)
            break;

        if(strcmp(head->next->last,name)==0)
        {
            temp = head->next;
            head->next = head->next->next;
            free(temp);
            n--;
        }
        else
            head = head->next;
    }
}

return first;

答案 1 :(得分:0)

首先,如果您使用head == NULL进行调用,则代码会崩溃,这很可能会发生(如果您的列表为空)。所以,检查一下。 其次,没有理由需要针对列表中的两个不同节点检查字符串name。只需跳过else if分支即可。 第三,如果你只想删除一个与你的测试匹配的节点,那么在删除它之后从while循环中断。

答案 2 :(得分:0)

您的删除代码中不需要else if条件。 如果多于一个元素正在删除,则意味着您的list包含多个具有相同名称的元素。 首先检查您的list内容。