C++ 链表定义赋值C++;

C++ 链表定义赋值C++;,c++,C++,我在大学的一项实验任务是将*.txt文件中的名称读入结构的链接列表,然后将列表传递给一个函数,该函数将名称打印到屏幕上。问题似乎是我在哪里分配了指针的值并将其传递给了我的函数。如果有人能指出我的错误,我将不胜感激 第h人: #ifndef PERSON_H #define PERSON_H #include<string> #include<fstream> #include<iostream> using namespace std; struct Per

我在大学的一项实验任务是将*.txt文件中的名称读入结构的链接列表,然后将列表传递给一个函数,该函数将名称打印到屏幕上。问题似乎是我在哪里分配了指针的值并将其传递给了我的函数。如果有人能指出我的错误,我将不胜感激

第h人:

#ifndef PERSON_H
#define PERSON_H
#include<string>
#include<fstream>
#include<iostream>
using namespace std;

struct Person
{
    Person *next;
    string name;
};

void walklist(Person *head_Ptr);

#endif PERSON_H
\ifndef PERSON\u H
#定义人
#包括
#包括
#包括
使用名称空间std;
结构人
{
人*下一位;
字符串名;
};
无效巡检名单(人员*负责人);
#endif PERSON_H
person.cpp:

#include "person.h"

void walklist(Person*head_Ptr)
{
    Person *cur;
    for (cur = head_Ptr; cur!=NULL; cur=cur->next)
    {
        cout<< cur->name<<endl;
    }
}
#包括“person.h”
无效巡检列表(人员*负责人)
{
个人*cur;
对于(cur=head\u Ptr;cur!=NULL;cur=cur->next)
{
coutname应该是吗

    temp_Ptr->next = nullptr;  // temp_Ptr will be the new last element
                               // so make sure that its next points to null

    if(last_Ptr != NULL)
    {
        last_Ptr->next = temp_Ptr; // Update next pointer of the current last
                                   // element to point to the new last element
    }

    last_Ptr = temp_Ptr;           // Update last to be the new element

    if(head_Ptr==NULL)
    {
        head_Ptr = temp_Ptr;       // Update head if needed (i.e. when null)
    }

看起来您走对了方向。错误出现在以下代码中:

    if(last_Ptr != NULL)
    {
        last_Ptr->next = temp_Ptr;
    }
    if(head_Ptr==NULL)
    {
        head_Ptr = last_Ptr;
    }

第一次到这里时,
last\u Ptr
head\u Ptr
都是空的。因此,跳过第一次赋值,然后将
last\u Ptr
赋值给
head\u Ptr
。然后它们仍然是
null
,有什么错误吗?打印错误吗?使用
使用命名空间;
不是个好主意。运行std使用调试器一步一步地编写代码,您将很容易在
infle中看到您的问题代码。good
循环有点奇怪。我知道问题就在这个循环中。我认为coutYou刚刚击败了我:-)尽管我不确定OP是否想要一个循环列表。@Stefan-感谢您不仅仅发布了相同的答案:-)不幸的是,有这么多用户这样做。甚至几分钟后。无论如何-关于
循环列表
,我认为这是一个bug,因为
walklist
的当前形式会有问题。你们太棒了!!!这是我这一整年唯一没能做的实验室,它正在摧毁我的灵魂!它工作得很好,你们甚至对它发表了评论e代码。谢谢你们一群绅士。那我该怎么办呢?你不需要在任何地方设置
last\u Ptr
。也许在添加第一个节点时,
last\u Ptr
head\u Ptr
应该是相同的?
    if(last_Ptr != NULL)
    {
        last_Ptr->next = temp_Ptr;
    }
    if(head_Ptr==NULL)
    {
        head_Ptr = last_Ptr;
    }