链接列表定义赋值C ++

时间:2016-01-31 13:15:38

标签: c++

我在大学的一项实验作业是将* .txt文件中的名称读取到结构的链接列表中,然后将列表传递给一个将名称打印到屏幕的函数。问题似乎是我已经指定了指针的值并将其传递给我的函数。如果有人能指出我出错的地方,我将不胜感激。

person.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

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;
    }
}

的main.cpp

#include<string>
#include<fstream>
#include<iostream>
#include"person.h"

using namespace std;

int main()
{
    string myfilename, names_in;

    cout<<"Please enter the name of the file to open";
    cin>>myfilename;

    fstream infile;
    infile.open(myfilename.c_str());

    if(infile.bad())
    {
        cerr<<"There has been a problem opening the file"<<endl;
        system("PAUSE");
        return -1;
    }

    Person *head_Ptr = NULL, *last_Ptr = NULL, *temp_Ptr;

    while(infile.good())
    {
        getline(infile, names_in);

        temp_Ptr = new Person;
        temp_Ptr->name = names_in;
        temp_Ptr->next = head_Ptr;

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

    walklist(head_Ptr);

    system("Pause");
    return 0;
}

2 个答案:

答案 0 :(得分:2)

不应该

    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)
    }

答案 1 :(得分:0)

好像你走在正确的轨道上。错误在此代码中:

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

第一次到达此处时,last_Ptrhead_Ptr均为空。因此,您跳过第一项作业,然后将last_Ptr分配给head_Ptr。然后他们仍然都是NULL