正在从循环双链接列表中删除节点

Deleting Node from Circular Doubly Linked List

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

我已经编写了将元素插入到循环双链接列表中并显示这些元素的代码。我还应该能够从列表中删除尾部节点,以及在列表中搜索特定元素。

这是我添加和打印的工作代码:

void Circular_DLList::add_to_tail(int a)
{
    DLLNode *temp = new DLLNode;
    temp->info = a;
    if (is_empty()) {   
        tail = temp;
        temp->next = tail;
        temp->prev = tail;
    }
    else {
        temp->next = tail->next;
        temp->prev = tail;
        tail = temp;
        tail->prev->next = temp;
    }
}
void Circular_DLList::print_list()
{
    DLLNode *ptr;
    ptr = tail->next;
    do {
        cout<< ptr->info << endl;
        ptr = ptr->next;
    }
    while(ptr != tail->next);
}

无论我为delete_from_tail函数写什么,它都会导致分段错误:11。这是我对函数(抛出错误)的尝试。

int Circular_DLList::delete_from_tail()
{
    int a = tail->info;
    if(tail == tail->next) {
        delete tail;
        tail = NULL;
    }
    else {
        tail = tail->prev;
        delete tail->next;
        tail->next = NULL;
    }
    return a;
}

任何关于如何解决这个问题的建议都是非常棒的。我试过调试,但我似乎不知道这个问题,也不知道它到底与哪里有关。感谢

如果仔细观察,这个问题非常明显。您的删除功能正在破坏链接列表的循环链。为什么呢请参阅下面的删除功能:

int Circular_DLList::delete_from_tail()
{
    int a = tail->info;
    DLLNode *temp;
    if(tail == tail->next) {
        delete tail;
        tail = NULL;
    }
    else {
        tail = tail->prev;
        delete tail->next;
        tail->next = NULL;
    }
    return a;
}

else-condition中,您正在设置tail->next = NULL,这实际上是错误,因此会破坏链。因此,当调用print时,它假设循环链是完整的,因此意外地试图访问NULL指针,这反过来又导致分段错误。

修复非常简单,请参阅以下代码:

int Circular_DLList::delete_from_tail()
{
    int a = tail->info;
    if(tail == tail->next) {
        delete tail;
        tail = NULL;
    }
    else {
        temp = tail;
        tail = tail->prev;
        tail->next = temp->next;        // To maintain the circular chain
        tail->next->previous = tail;    // Since this element's previous also point to the node about to be deleted
        delete temp;
        temp = NULL;
    }
    return a;
}