链接列表输出崩溃

时间:2011-12-02 00:31:42

标签: c++ linked-list

我的程序在输出链接列表的内容时挂起。我无法更改标题,只能更改cpp文件。

playlist.h:

class PlayList {
    private:

    struct SongNode {
        Song data;
        SongNode* next;
        SongNode (const Song& s, SongNode* nxt = 0)
          : data(s), next(nxt)
        {}
    };

    friend std::ostream& operator<< (std::ostream& out, const PlayList& s);

    SongNode* first; // head of a list of songs, ordered by title, then artist
    //Snip...

    inline
    std::ostream& operator<< (std::ostream& out, const PlayList& pl)
    {
        for (PlayList::SongNode* current = pl.first; current != 0; current = current->next)
            out << current->data << std::endl;
        return out;
    }

playlist.cpp

using namespace std;



PlayList::PlayList()
    : totalTime(0,0,0)
{
}


void PlayList::operator+= (const Song& song)
{
    SongNode* newNode = new SongNode(song, first);
    first = newNode;
}

当输出列表时,应该打印的所有数据都会打印,但程序会挂起。

2 个答案:

答案 0 :(得分:6)

class PlayList的构造函数中,您需要初始化first

public:
    PlayList() : first(NULL) {}

否则,在operator<<中,您到达列表的末尾,而不是遇到NULL,您只会得到一个垃圾指针。

答案 1 :(得分:4)

您忘记在构造函数中初始化first