c++打印链表

C++ print a linked list

本文关键字:链表 打印 c++      更新时间:2023-10-16

我是c++的新手,我的打印功能有问题。这可能是一个非常简单的问题,但我不知道如何解决它。

在我开始写代码之前,我可能会补充一下,这应该是一个循环列表。

首先,这是我的链表结构
struct CL;
typedef CL* list_type;
struct person
{
    string last_name;
    string first_name;
    string tel_nr;
};
struct CL
{
    person data;
    list_type next;
};
如您所见,我希望列表包含一个data和一个指针。数据是一个人(姓、名和电话号码(作为字符串))。

我的主程序是这样的

int main ()
{
    list_type list;
    list_type first;
    string line;
    person info;
    ifstream myfile ("INFILE.TXT");
    if (myfile.is_open())
    {
        while (myfile.good())
        {
            getline (myfile,line,',');
            info.last_name=line;
            getline(myfile,line,' ');
            getline(myfile,line,':');
            info.first_name=line;
            getline(myfile,line);
            info.tel_nr=line;
            if(first==0)
            {
                list = new CL;
                first = list;
                list->data = info;
                list->next = 0;
            }
            else
            {
                list->next = new CL;
                list = list->next;
                list->data = info;
                list->next = 0;
            }
        }
        list->next = first;
        print(list);
        myfile.close();
    }
    else cout<<"Unable to open file.";
    return 0;
}

现在是我遇到问题的部分,打印功能。

void print(CL* cur)
{
    list_type first;
    first=cur;
    int x;
    do
    {
        cout<<"n"<<"Your Data is: ";
        cout<<cur->data.last_name<<cur->data.first_name<<cur->data.tel_nr;
        //I guess this is where the fault lies ^.
        cur = cur->next;
    }
    while(cur != first);
}

如果可能的话,我想要一个解释,而不仅仅是正确的代码。

感谢

编辑。我得到的结果是很多奇怪的字符,比如:

ê,(,?,ý and alot of other characters I don't know how to type.

我期望的结果是这样的

Robertson Linda 0838-2345
Brown Charles 068-24567
etc until the end of list

Edit2 .

解决了,谢谢。

第一个问题

int main ()
{
    list_type list;
    list_type first; // uninitialized value
    // ...
            if(first==0) // ???
            {

你需要显式地初始化first来做你期望的事情:

int main ()
{
    list_type list;
    list_type first = 0;
    // ...
            if(first==0)
            {

第二个问题

你的链表代码首先是脆弱的,因为你并不是真正在写c++。即使不使用STL,您的列表也可以(并且应该)提供某种程度的抽象。实际上,正确地编写它更容易,因为您的数据结构逻辑不会与测试工具或问题域逻辑完全混淆。

例如,

class PersonList {
    CL *head;
    CL *tail;
public:
    PersonList(); // think about how to initialize an empty list
    void push_back(Person const&); // head & tail modified in here
    // etc.
};

注意,如果不允许使用class,这是相同的:

struct PersonList {
private:
    CL *head;
    // ... as above ...

,如果不允许使用构造函数&一个好的c风格等效方法可能是:

struct PersonList {
    CL *head;
    CL *tail;
};
struct PersonList * new_list();
void push_back(struct PersonList *, Person const &);

这仍然将您的数据结构代码分组在一个地方,远离您的业务逻辑/问题域/测试工具代码。

将first初始化为0。因为第一个链接没有初始化,所以会出现坏字符