繁体   English   中英

排序链表析构函数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;
}

我认为我的问题可能出在析构函数上,但是每次我尝试不同的操作时,都会遇到相同的错误。

没有足够的声誉来发表评论,因此发布了一个新帖子。

  1. 您没有提供printList()函数的定义,也没有提供Movies.h的内容,它们也可能有问题。
  2. 在“电影”析构函数中,您使用“临时”存储需要删除的当前磁头,而不是删除currentPos。
  3. 在insertMovie函数中,如果“ currentPos-> movieName> = tempPtr-> movieName”为true,则您是从while循环中断开而没有将其插入列表中,而是每次都增加长度。

希望这可以帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM