删除循环双向链表中的节点

Removing a node in a circular doubly linked list

本文关键字:节点 双向链表 循环 删除      更新时间:2023-10-16

我正在尝试编写一些代码来从循环双向链表中删除节点。我编写了以下函数,它主要有效:

bool Circular::remove(int index)
{
    if (head == NULL)
        return false;
    Node* current;
    current = head;
    if (index > 0)
    {
        for (int i = 0; i < index; i++)
        {
            current = current->next;
        }
    }
    else if (index < 0)
    {
        for (int i = 0; i < abs(index); i++)
        {
            current = current->prev;
        }
    }
    if (current == head)
    {
        head = current->next;
    }
    else if (current == tail)
    {
        tail = current->prev;
    }
    current->prev->next = current->next;
    current->next->prev = current->prev;
    return true;
}

我唯一的问题是,当我将数字 1 传递到索引号中时,它不会删除正确的值。相反,它总是删除尾巴。如果您认为我的代码在其他地方有问题,那么我也会调查一下。

我想

我已经想通了。大多数情况下,我使用功能来移除头部...

Node* temp = head;
head = head->next;
head->prev = tail;
tail->next = head;
delete temp;
return true;

。并移除尾巴:

Node* temp = tail;
tail = tail->prev;
tail->next = head;
head->prev = tail;
delete temp;
return true;

显然,仅仅在头部和尾部移动并不足以实际删除这些节点。