首页 > 解决方案 > 字符串不会存储在链表中

问题描述

#include <iostream>
#include <string.h>

using namespace std;

class MovieList {
    private:
    struct MovieNode {
        string title;
        struct MovieNode *next;
    };

    MovieNode *head;
       
    public:
    void appendNode(string var);
    void displayList();
};
    
void MovieList::appendNode(string var) {
    MovieNode *newNode, *nodePtr;

    newNode = new MovieNode;
    newNode->title = var;
    newNode->next = NULL;

    if (!head) {
        head = newNode;
    }
    else {
        nodePtr = head;

        while (nodePtr->next)
            nodePtr = nodePtr->next;

        nodePtr->next = newNode;
    }

    cout << endl << "Input has been successfull!" << endl;
}

void MovieList::displayList() {
    MovieNode *nodePtr;

    if (head == NULL) {
        cout << "The list is empty!" << endl;
    }
    else {
        cout << "The nodes in the List are... " << endl;
        nodePtr = head;
        while (nodePtr) {
            cout << nodePtr->title << endl;
            nodePtr = nodePtr->next;
        }
    }
}

int main() {
    MovieList list;
    string var;
    cout << " << Enter Movie >> " << endl << endl;
    cout << "Enter a movie: ";
    getline(cin, var);
    list.appendNode(var);
    list.displayList();
}

我的问题是为什么字符串变量不会显示在显示空白中。当我尝试输入字符串时,代码开始工作,但随后退出程序而不显示我输入的内容。我如何放置字符串或者将字符串实现到节点中是否有问题?请帮忙,我是链表中的新手。

标签: c++linked-list

解决方案


一个问题是创建对象MovieList.head时未初始化。MovieList

因此,当MovieList.append()被调用时,这一行:

 if (!head)

导致程序的行为不稳定,因为head指针是任何值,您不知道该值是什么。它可能nullptr,因此程序可以工作,但它可能是任何其他值。

底线是您应该在创建对象时初始化您的成员变量。您可以创建一个已初始化的默认构造函数head,也可以head在声明点直接内联初始化:

class MovieList
{
   private:
       struct MovieNode
       {
            string title;
            struct MovieNode *next;
       };
       MovieNode *head;
   public:
       MovieList() : head(nullptr) {}  // Using constructor
       void appendNode(string var);
       void displayList();
};

或者:

class MovieList
{
   private:
       struct MovieNode
       {
            string title;
            struct MovieNode *next;
       };
       MovieNode *head = nullptr;   // Initialized here
   public:
       void appendNode(string var);
       void displayList();
};

推荐阅读