删除双向链表中的最后一个元素时读取访问冲突

时间:2017-10-03 05:03:15

标签: c++ access-violation doubly-linked-list

我在BufferedInputStream方法中为我的双向链表找到了一个例外:

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.

删除节点的代码:

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

在函数调用时,链表包含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; } } }

请建议如何修复此代码(最好没有异常处理程序)。

1 个答案:

答案 0 :(得分:0)

此函数中出现错误,但错误发生在其他地方。 您在#!/bin/bash set -e declare -a myarray readarray myarray < file_pathname # Include newline. readarray -t myarray < file_pathname # Exclude newline. new_string=admin1 for s in ${myarray[@]}; do echo $s; echo ${s/admin/$new_string} done 上收到此错误,这意味着此指针指向delete tail_->next

问题可能出在你的插入方法中。插入的节点未指向前一个元素。

我的建议是调试插入方法并检查指针是否设置正确。