I got an exception in pop_back()
method for my doubly linked list:
我的双向链表中的pop_back()方法有异常:
Exception thrown: read access violation.
this->tail_ was nullptr.
If there is a handler for this exception, the program may be safely continued.
Code for adding a new node and setting the pointers
用于添加新节点和设置指针的代码
void push_front(const T& data) {
//make a node
Node* nn = new Node(data, head_);
if (head_ != nullptr) {
head_->prev_ = nn;
}
else {
tail_ = nn;
}
head_ = nn;
}
// Runtime: Linear
void push_back(const T& data) {
Node* nn = new Node(data);
if (head_!=nullptr) {
tail_->next_ = nn;
}
else {
head_ = nn;
}
tail_ = nn;
}
Code for the delete node:
删除节点的代码:
void Sentinel<T>::pop_back() {
if (head_) { // if list is not empty
if (head_ != tail_) { // if there is more than one node
tail_ = tail_->prev_;
delete tail_->next_; //error is here
tail_->next_ = nullptr;
}
else {
delete tail_;
head_ = tail_ = nullptr;
}
}
}
At the moment of the function call the linked list contains 1 0 0 0 3 4
.
在函数调用时,链表包含1 0 0 0 3 4。
Please advice how to fix this code (preferably without the exception handler).
请建议如何修复此代码(最好不要使用异常处理程序)。
1 个解决方案
#1
0
The error appears in this function but the bug is elsewhere. You get this error on delete tail_->next
which means that this pointer is pointing to nullptr
.
错误出现在此函数中,但错误发生在其他地方。你在delete tail _-> next上得到这个错误,这意味着这个指针指向nullptr。
The problem is probably in your insert method. The inserted node is not pointing to the previous element.
问题可能在于您的插入方法。插入的节点未指向前一个元素。
My advice is to debug your insert method and check if the pointers are set correctly.
我的建议是调试你的insert方法并检查指针是否设置正确。
#1
0
The error appears in this function but the bug is elsewhere. You get this error on delete tail_->next
which means that this pointer is pointing to nullptr
.
错误出现在此函数中,但错误发生在其他地方。你在delete tail _-> next上得到这个错误,这意味着这个指针指向nullptr。
The problem is probably in your insert method. The inserted node is not pointing to the previous element.
问题可能在于您的插入方法。插入的节点未指向前一个元素。
My advice is to debug your insert method and check if the pointers are set correctly.
我的建议是调试你的insert方法并检查指针是否设置正确。