首页 > 解决方案 > 如何从C中的链表中删除特定节点?

问题描述

以下代码从列表中删除特定整数,但我想删除一个 char 数组。任何人都可以帮助我如何修改此代码,以便它删除一个 char arr[]

void removeSpecific(int delValue)
{
    struct node *temp1 = head;  //temp1 Keeps track of the current node
    struct node *temp2 = NULL;  //temp2 Keeps tract of the previous node

    if(temp1->num == delValue)  //Special case: If the item is in the start node
    {
        struct node *temp3 = head; 
        head=head->next;
        free(temp3);         
    }
    else
    { 
        while(temp1->num != delValue) //If the number is not present in the current node
        {                             // we move to the next node
            if(temp1 -> next == NULL)
            {
                printf("\nGiven node not found in the list!!!");
                exit(1); 
            }
            temp2 = temp1;         // Add of 6  next -> 8 ->next  ------- 9
            temp1 = temp1 -> next; // temp1 - Add of 8
        }

        temp2 -> next = temp1 -> next; // removing the node

        free(temp1);
        free(temp2);

        printf("\nOne node deleted!!!\n\n");
    }
}


标签: c

解决方案


如果要删除 num 为 a 的 struc ,char[]针为 a char *,您可以使用strcmp

在删除第一个元素的情况下,我将消息移出 else 以获取它

void removeSpecific(const char* delValue)
{
    struct node *curr = head;
    struct node *prev = NULL;

    if(!strcmp(curr->num, delValue))
    {
        struct node *tmp = head; 
        head=head->next;
        free(tmp);
    } else { 
        while(strcmp(curr->num, delValue)) {
            if(curr -> next == NULL)
            {
                printf("\nGiven node not found in the list!!!");
                exit(1); 
            }
            prev = curr;
            curr = curr -> next;
        }

        prev -> next = curr -> next; // removing the node

        free(curr);
    }
    printf("\nOne node deleted!!!\n\n");

}

推荐阅读