【发布时间】: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