循环双链表 - 分段故障:11 [英] Circular Doubly Linked List - Segmentation fault: 11
问题描述
我想实现一个循环双向链表,但我不断得到一个分段错误:11错误(我相信这是因为添加和删除功能)。我不知道我的代码是否是接近,但我不能通过这个错误,测试它正确。这是我相信涉及的代码:
(Circular_DLList.cc)
void Circular_DLList :: add_to_tail(int a)
{
if(is_empty()){
tail = new DLLNode(a);
tail-> next = tail;
}
else {
tail-> next = new DLLNode(a,tail-> next);
}
}
int Circular_DLList :: delete_from_tail()
{
if(!is_empty())
{
int a = tail-> info;
tail = tail-> prev;
tail-> next = null;
return a;
}
else
{
tail = 0;
}
return a;
}
任何帮助将是太棒了,谢谢。
代码中有多个问题,但这里有其中一个问题。
添加第一个元素时,您可以:
tail = new DLLNode(a);
tail-> next = tail;
,所以你留下 prev
等于 0
(BTW:使用 nullptr
而不是 0
p>
如果您随后删除该元素:
int a = tail - > info;
tail = tail-> prev; // tail become 0
tail-> next = null; // Dereference 0 cause seg fault
return a;
BTW:您的删除函数也应该删除 DLLNode
!只需更改指针值是不够的。
因此,这会导致3个更改:
新元素一定要始终设置两者 下一页
和上一页
2)请记得删除 DLLNode
用新的
你的删除函数你需要一个特殊的情况下检查列表是否只包含一个元素,即 if(tail == tail-> next){..删除最后一个元素.. set tail equal nullptr}
I'm trying to implement a circular doubly linked list but I keep getting a segmentation fault: 11 error (I believe it's because of the add and delete functions). I have no idea whether my code is even close, but I can't get past this error to test it properly. This is the code I have that I believe is involved:
(Circular_DLList.cc)
void Circular_DLList::add_to_tail(int a)
{
if (is_empty()) {
tail = new DLLNode(a);
tail->next = tail;
}
else {
tail->next = new DLLNode(a, tail->next);
}
}
int Circular_DLList::delete_from_tail()
{
if(!is_empty())
{
int a = tail->info;
tail = tail->prev;
tail->next = null;
return a;
}
else
{
tail = 0;
}
return a;
}
Any help would be fantastic, thanks.
There is more than one problem in your code but here is one of them.
When you add the first element, you do:
tail = new DLLNode(a);
tail->next = tail;
so you leave prev
equal to 0
(BTW: use nullptr
instead of 0
).
If you then delete the element you do:
int a = tail->info;
tail = tail->prev; // tail becomes 0
tail->next = null; // Dereference 0 cause seg fault
return a;
BTW: Your delete function should also delete the DLLNode
! Just changing pointer values isn't sufficient.
So this leads to 3 changes:
1) When adding new elements make sure to always set both next
and prev
2) Remember to delete the DLLNode
created with new
3) In your delete function you need a special case for checking whether the list contains exactly one element, i.e. if (tail == tail->next) { .. delete last element .. set tail equal nullptr}
这篇关于循环双链表 - 分段故障:11的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!