我正在做一个双向链表,我正在做pop_front函数。当列表中只有一个节点时,删除节点时会遇到一些问题。
int main()
{
ForwardList<int> l;
l.push_back(1);
l.push_back(2);
l.push_back(3);
l.push_back(4);
l.push_back(5);
l.pop_front();
l.pop_front();
l.pop_front();
l.pop_front();
l.pop_front();
}
void pop_front()
{
if (!empty())
{
if (this->head == this->tail)
{
delete this->head;
delete this->tail;
this->head = nullptr;
this->tail = nullptr;
}
else
{
this->head = this->head->next;
delete this->head->prev;
this->head->prev = nullptr;
}
}
}
我收到此错误:
a.out(69846,0x10d5105c0) malloc: *** error for object 0x7fa7a2c02b50: pointer being freed was not allocated
a.out(69846,0x10d5105c0) malloc: *** set a breakpoint in malloc_error_break to debug
[1] 69846 abort ./a.out
答案 0 :(得分:3)
if (this->head == this->tail)
{
delete this->head;
delete this->tail;
this->head = nullptr;
this->tail = nullptr;
}
看看这些行,因为this-> head == this-> tail,所以delele this-> head和delete this-> tail两次删除了相同的指针。
答案 1 :(得分:0)
除了@duyue答案外,更好的设计是将节点取消链接和处置拆分为单独的功能。参见示例here。