【问题标题】:Sorted Linked List Destructor c++排序链表析构函数 c++
【发布时间】:2019-04-09 10:54:30
【问题描述】:

我目前正在开发一个将电影标题添加到排序链接列表的程序,并且我一直在运行“分段错误: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;
}

我认为我的问题可能与我的析构函数有关,但每次我尝试不同的东西时都会遇到相同的错误。

【问题讨论】:

  • 使用调试器单步调试您的代码。

标签: c++ list sorting linked-list destructor


【解决方案1】:

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

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 2014-12-15
    • 2015-08-03
    • 2013-04-26
    • 1970-01-01
    • 2020-10-07
    • 1970-01-01
    相关资源
    最近更新 更多