无法插入并打印出链表

时间:2019-05-17 04:30:00

标签: c++11

我正在尝试创建一个简单的链表类。该程序运行,但输出错误。似乎链表没有按我的要求插入新节点。

class Node
{
public:
    std::string name;
    Node *next;
};

class ProductName
{
private:
    Node *head;
public:
    ProductName()
    {
        head = NULL;
    }
    void insertNode(std::string input)
    {
        Node *temp;
        temp = new Node;
        temp->name = input;
        temp->next = head;
        head = temp;
    }
    void printOut()
    {
        Node *p;
        p = head;
        while (p->next != NULL)
        {
            std::cout << p->name << " ";
            p = p->next;
        }
    }
};

int main()
{
    ProductName object;
    object.insertNode("Hello");
    object.insertNode("world!");
    object.printOut();
}

我希望输出为Hello world!,但它会打印出一串随机字符005C4BA0

编辑:我忘记了指针...在打印功能中它是p->name而不是p。但是,现在我的结果是world!

1 个答案:

答案 0 :(得分:0)

第一个问题:您总是会通过替换head插入开头。如果您希望节点按插入顺序显示,则应在最后插入节点:

class ProductName
{
private:
    Node *head;
    Node *tail; // additional member to track the last node
public:
    ProductName()
        : head(nullptr), tail(nullptr)
    { }

    void insertNode(std::string input)
    {
        Node *temp = new Node{ std::move(input), nullptr };
        if (tail) {
            tail->next = temp;
            tail = temp;
        } else {
            head = tail = temp;
        }
    }
}

第二个问题:您正在打印所有带有next的元素,这意味着将不打印最后一个元素。

void printOut()
{
    Node *p = head;
    // print while p != nullptr
    // this also properly handles the empty list when head == nullptr
    while (p)
    {
        std::cout << p->name << " ";
        p = p->next;
    }
}