c++ - 从链表中删除节点时出错

标签 c++ linked-list

我有:

class Node {
   int* vec;
   Node* next;
};

Class LinkedList{
   Node* head;
}

我创建了一个函数来找到我要删除的节点:

Node* tmp = find("abc");

我订购了指针并对其进行了调试,一切正常。

现在我必须删除 tmp,所以我尝试了:

delete[] tmp->vec;
delete tmp; // here I get an error window.

为什么?

这是我的真实代码:

class Show_Time
{
  private:
    string movieCode;
    string movieName;
    string time; //the time of screening the movie.
};


class Time_LinkedList
{
 private:
    class Time_Node
    {
     public:
        Show_Time* data;
        Time_Node* prev;
        Time_Node* next;
     public:
        Time_Node(string movie_code, string movie_name, string time_of_movie); //"Time_Node" constructor
        ~Time_Node();//"Time_Node" destructor
    };
    Time_Node* head; //pointer to the first node in the linkedlist
};


void Time_LinkedList::delete_TimeNode(string movieCode, string time)
{
    Time_Node* tmp = find_Time_Node(movieCode,time);

    // the case that there is one element in the list
    if (tmp->prev == NULL && tmp->next == NULL)
    {
        head = NULL;
    }

    // the case that it's the first element of the list
    else if (tmp->prev == NULL)
    {
        head = tmp->next;
        tmp->next->prev = head;        
    }

    // the case that it's the last element of the list
    else if (tmp->next == NULL)
    {
        tmp->prev->next = NULL;
    }

    // there are element in the left and right of the element
    else
    {
        tmp->prev->next = tmp->next;
        tmp->next->prev = tmp->prev;
    }

    // delete the temp and its data
    delete tmp->data;
    delete tmp;
}

最佳答案

因此,根据您的回复,您的问题是您正在进行双重删除,即undefined behavior .您应该从 Time_LinkedList::delete_TimeNode 中删除 delete data 并让析构函数完成它的工作。

关于c++ - 从链表中删除节点时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15801525/

相关文章:

c++ - 在 Unix 下的 c++ 中捕获进程终止

c++ - vector<shared_ptr<X>> copying-调用了X构造函数?

c++ - C++ 中的 LNK2019 错误

c - c中的malloc链表

c - 如何在C中将链表中的字符复制到数组中?

c - 在 C 中传递链表时如何解决这些冲突类型错误?

c++ - 如何将 std::chrono::high_resolution_clock::now() 转换为毫秒、微秒...?

c++ - C/C++ 将字符串放入二维数组?

java - 我的反转链表的代码有什么问题?

c - 关于 scanf() 的奇怪跳过