C-链表-删除节点

C-链表-删除节点,c,linked-list,nodes,C,Linked List,Nodes,假设删除包含与字符串“name”相同的数据“last”的所有节点。它没有给我一个错误,但它工作不正常。它删除的内容超过了需要删除的内容 struct node* mydelete(struct node *head) { char name[21]; struct node *temp; printf("---Please enter last name:"); scanf("%s", &name); while (head->next !

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

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;
}

首先,如果使用
head==NULL
调用,代码会崩溃,这很可能发生(如果列表为空)。所以,检查一下。 其次,没有理由需要对照列表的两个不同节点检查字符串
name
。如果分支,只需跳过
else。

第三,如果您只想删除一个与测试匹配的节点,那么在删除它之后,请中断while循环。

您不需要删除代码中的
else if
条件。 如果有多个元素正在删除,则表示您的
列表中包含多个同名元素。
首先检查您的
列表
内容

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;

您是否也可以发布测试用例和执行结果?我正在尝试删除所有包含“name”@user3053814的节点。我有一个错误:“bread”应该是“break”。代码已更正。