排序链表析构函数 C++

Sorted Linked List Destructor c++

我目前正在开发一个将电影片名添加到排序链表的程序,我保留 运行 "Segmentation fault: 11" 但我不知道它来自哪里。这是我的规范文件和客户端代码。

#include <string>
#include <iostream>
#include "Movies.h"
using namespace std;
struct NodeList {
    string movieName; //data
    NodeList* next; //points to next item
};

Movies::Movies()
{
    headOfList = NULL;
    length = 0;
    currentPos = NULL;
}
void Movies::insertMovie(string movieName)
{
    NodeList* tempPtr = new NodeList;
    tempPtr->movieName = movieName;
    if(headOfList == NULL)
    {
        headOfList = tempPtr;
    }
    else {
        currentPos = headOfList;
        NodeList* trail = NULL;
    while(currentPos != NULL)
    {
        if(currentPos->movieName >= tempPtr->movieName)
        {
            break;
        }
        else
        {
            trail = currentPos;
            currentPos = currentPos->next;
        }
        if(currentPos == headOfList) {
            tempPtr->next = headOfList;
            headOfList = tempPtr;
        }
        else {
            tempPtr->next = currentPos; 
            trail->next = tempPtr;
        }
       }
      }
       length++;
    }

Movies::~Movies()
{
    NodeList* temp;
    while(headOfList != NULL)
    {
        temp = headOfList;
        headOfList = headOfList->next;
        delete currentPos;
    }
}

然后这是我的客户

#include <iostream>
#include <string>
#include "Movies.h"
using namespace std;
int main()
{
    Movies myMovieList;

    myMovieList.insertMovie("Harry Potter");
    myMovieList.printList();
    return 0;
}

我想我的问题可能出在我的析构函数上,但每次我尝试不同的方法时,我都会得到同样的错误。

没有足够的声誉来评论,因此一个新的 post。

  1. 您没有提供 printList() 函数的定义以及 Movies.h 的内容,这也可能存在问题。
  2. 在 Movies 析构函数中,您使用 "temp" 存储需要删除的当前头,而不是删除 currentPos。
  3. 在 insertMovie 函数中,如果 "currentPos->movieName >= tempPtr->movieName" 为真,您将退出 while 循环而不将其插入列表,但每次都会增加长度。

希望对您有所帮助。