c++ - 从循环双向链表中删除节点

标签 c++ linked-list segmentation-fault doubly-linked-list circular-list

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

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

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;
}

关于c++ - 从循环双向链表中删除节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36324417/

相关文章:

c++ - 为什么有两个 std::allocator::construct 函数?

c++ - 此代码显示错误 "stu undeclared"??我应该怎么办

c - 创建链接列表时出现神秘的段错误(添加功能)

java - Java中以节点为参数的链表递归

python - 在 Python 中导入某些库时发生的段错误?

c++ - QApplication构造函数段错误

c++ - 尝试输入结构 vector 内的结构成员会导致段错误

c++ - C++ 中有什么方法可以转发声明函数原型(prototype)?

c++ - 在 GDB 中调试生成的代码时显示原始源代码

java - 尝试将节点添加到链表中