C ++打印链表

时间:2013-02-28 16:15:26

标签: c++ linked-list

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

如您所见,我希望列表包含数据和指针。数据是一个人(姓氏,名字和电话号码(作为字符串))。

我的主程序看起来像这样

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。

解决了,很多。

2 个答案:

答案 0 :(得分:2)

第一个问题

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

如果你不被允许使用构造函数&amp;方法,一个好的C风格的等价物可能是:

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

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

答案 1 :(得分:0)

首先初始化为零。你得到了不好的字符,因为第一个链接没有被初始化。

相关问题