正在从循环双链接列表中删除节点
Deleting Node from Circular Doubly Linked 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++中删除一个项目
- C++如何通过用户输入删除列表元素
- 从嵌套在std::映射中的std::列表中删除元素的最佳方式
- 删除列表中的第n个元素
- 你能检查一下为什么在这个代码中从链接列表中删除项目不起作用吗
- 从类型列表中递归删除重复项会导致编译器堆空间错误 (VS2017)
- 如何在不强制转换每个参数的情况下删除初始值设定项列表中从 int 到 char 的缩小转换?
- 删除列表 c++ 中的最后 3 个元素
- 为什么每当我尝试运行此链接列表删除功能时都会收到分段错误错误?
- 我可以从列表中获取对象并复制它们,但如何删除我复制的对象?
- 动态分配列表 - 创建一个函数,用于删除所有包含偶数值的元素
- C++ 从具有开始位置和结束位置的列表中删除
- 从列表向量中删除无法按预期工作
- 从列表C++中删除对象
- 简单的链接列表删除失败
- C++循环链接列表 - 删除所有节点
- 链接列表删除节点C
- 链接列表删除
- 矢量与来自 STL 的列表 - 删除方法
- 运算符== 和列表::删除()