如何从c中的双向链表中删除节点

问题描述 投票:-2回答:2

我正在研究c中的双向链表,我有一个带有20个节点的双重链接tepm2,我想删除用户插入单词的节点。

struct node {
    struct node *prev;
    char word[100];
    int repeatTime;
    struct node *next;
} *h, *temp, *temp1, *temp2;

每个节点都有唯一的单词。

printf("\n Enter word to delete  : ");
scanf("%s", &word);
Delete(word);

int delete(char data[200]) {      //unable to delete
    if (h == NULL)
        return;

    temp2 = next = previous = h;

    while (temp2->next != NULL) {
        if ((strcmp(temp2->word, data) == 0)) {
            if (temp2->prev == NULL) {
                h = temp2->next;
                free(temp2);
                return;
            } else if (temp2->prev == NULL) {
                previous->next = temp2;
                free(temp2);
                previous->next = NULL;
                return;
            } else {
                previous->next = temp2->next;
                next->prev = temp2->next;
            }
        }

        temp2 = temp->next;
    }
}

我无法删除word用户输入的特定节点

c linked-list
2个回答
0
投票

试试这个:

int delete(const char *data)
{
    struct node *temp = h;

    if (h == NULL) return;

    while (temp->next != NULL)
    {
        if (strcmp(temp->word, data) == 0)
        {
            if (temp->prev != NULL)
            {
                temp->prev->next = temp->next;
            }
            if (temp->next != NULL)
            {
                temp->next->prev = temp->prev;
            }
            if (h == temp)
            {
                h = temp->next;
            }
            free(temp);
            return;
        }
        temp = temp->next;
    }
}

0
投票

首先,我不认为这是正确的temp2 = next = previous = h;

现在你所要做的就是通过遍历找到你要删除的节点,然后将它的prev节点链接到它的下一个节点,即(temp2-> prev) - > next = next和(temp2-> next) - > prev =上一个并且释放它。

现在真正的问题在于1.第一个节点后面有其他节点2.最后一个节点,其前面有其他节点3.只有节点

您可以通过将它们转换为前一个问题来简化所有这三个问题,即我们刚刚解决的中间问题中的节点。

为简化起见,您可以将头部和尾部都设为NULL。

© www.soinside.com 2019 - 2024. All rights reserved.