簡體   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