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

时间:2016-03-04 06:13:02

标签: c++ doubly-linked-list circular-list

我试图编写一些代码来从循环双向链表中删除节点。我写过以下函数,主要有用:

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传递给索引号时,它不会删除正确的值。相反,它总是删除尾巴。如果您认为我的代码在其他地方出现了问题,那么我也会调查它。

1 个答案:

答案 0 :(得分:0)

我想我已经弄明白了。大多数情况下,我使用功能去除头部......

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;

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