链表返回空列表

问题描述 投票:0回答:1

我在链表的头部插入节点,并使用 print() 方法打印每个节点。

每个节点由两 (2) 个字符串和一 (1) 个整数组成。

链表插入似乎按预期工作。但是,在调试代码时,链接列表中没有打印或显示任何内容。

任何人都可以找到为什么链接列表没有显示任何数据或没有被打印吗?

#include <iostream>
#include <string>

class Node
{
    public:
        std::string name;
        std::string ipaddress;
        int iD;
        Node* next = NULL;

        Node(std::string name, std::string ipaddress, int iD)
        {
            this->name = name;
            this->ipaddress = ipaddress;
            this->iD = iD;
        }
};

class OfficeSpace
{
    public:
        Node* head = NULL;

        void insert (std::string name, std::string ipaddress, int iD)
        {
            Node* node = new Node(name, ipaddress, iD);
            node->next = head;
            head = node->next;
        }

        void print()
        {
            Node* temp = head;
            while (temp != NULL)
            {
                std::cout << temp->name << std::endl << temp->ipaddress << 
                    "iD: " << temp->iD << std::endl;
                temp = temp->next;
            }
            std::cout << std::endl;
        }
};

int main(void)
{
    OfficeSpace office;

    office.insert("Peter", "20.3.45.7", 22422);
    office.insert("Samir", "20.3.45.2", 25233);
    office.insert("Lawrence", "20.3.44.10", 27465);
    office.insert("Joanna", "20.3.44.8", 24544);
    office.insert("Bill Lumbergh", "20.3.44.12", 22445);
    office.insert("Tom Smykowski", "20.3.35.4", 26464);
    office.insert("Milton", "20.3.35.9", 24645);

    office.print();

    return 0;
}

我尝试将预期的变量传递到office.insert(..)方法中,但我遇到了同样的问题。

c++ string linked-list pass-by-value scope-resolution-operator
1个回答
0
投票

OfficeSpace::insert
的这些行中:

            node->next = head;
            head = node->next;

您首先将

node->next
设置为
head
(
NULL
),然后将
head
设置为
node->next
(在前一行中设置为
NULL
)。

您应该将

node->next
分配给变量
node
,而不是
head

最新问题
© www.soinside.com 2019 - 2024. All rights reserved.