链接列表输出崩溃

mcu*_*001 4 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;
    }
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

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

Ant*_*ony 6

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

public:
    PlayList() : first(NULL) {}
Run Code Online (Sandbox Code Playgroud)

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