循环打印垃圾c ++的链表

时间:2018-02-05 02:05:48

标签: c++ printing linked-list

我正在使用链接列表来模拟计算机实验室,我正在尝试打印链接列表。使用cout进行打印存在问题,它会产生垃圾,直到终端放弃并发送分段错误11。

#include <iostream>
#include <string>

using namespace std;

struct lab {
    string current_ID;
    int station_number;
    lab *link;
};

typedef lab* lab_ptr;


void print_status(lab_ptr& head1, lab_ptr& head2, lab_ptr& head3, lab_ptr& head4);

int main()
{
    lab_ptr head_lab_1;
    head_lab_1 = new lab;

    lab_ptr head_lab_2;
    head_lab_2 = new lab;

    lab_ptr head_lab_3;
    head_lab_3 = new lab;

    lab_ptr head_lab_4;
    head_lab_4 = new lab;

    set_up_linked_list_for_n_stations(head_lab_1, 5);
    set_up_linked_list_for_n_stations(head_lab_2, 6);
    set_up_linked_list_for_n_stations(head_lab_3, 4);
    set_up_linked_list_for_n_stations(head_lab_4, 3);


    return 0;
}



void set_up_linked_list_for_n_stations(lab_ptr& head, int n)
{
    lab_ptr curr;
    curr = new lab;

    for(int j = 0; j < n; j++)
    {
        lab_ptr temp = new lab;
        temp->link = NULL;
        temp->station_number = n+1;
        temp->current_ID = 'empty';

        cout << temp->station_number << " " << temp->current_ID << endl;

        if(head != NULL)
        {
            curr = head;
            while(curr->link != NULL)
            {
                curr = curr->link;
            }
            curr->link = temp;
        } else
        {
            head = temp;
        }
    }
}

这是我第一次使用链表,所以错误可能是我错过的非常明显的错误。如果这是一个愚蠢的错误,对不起。

2 个答案:

答案 0 :(得分:0)

对于字符串成员current_ID,您需要使用双引号传递值:

print( )

变为

temp->current_ID = 'empty';

你还需要在main()之前移动函数void set_up_linked_list_for_n_stations(lab_ptr&amp; head,int n)

答案 1 :(得分:0)

您正在进行额外分配,其他地方列表未正确初始化。将head_lab_1初始化为nullptr(或仅NULL

在函数set_up_linked_list_for_n_stations中删除curr = new lab

void set_up_linked_list_for_n_stations(lab_ptr& head, int n)
{
    for(int j = 0; j < n; j++)
    {
        lab_ptr temp = new lab;
        temp->link = NULL;
        temp->station_number = n + 1;
        temp->current_ID = "empty";
        cout << temp->station_number << " " << temp->current_ID << endl;

        if(head != NULL)
        {
            lab_ptr curr = head;
            while(curr->link != NULL)
            {
                curr = curr->link;
            }
            curr->link = temp;
        }
        else
        {
            head = temp;
        }
    }
}

int main()
{
    lab_ptr head_lab_1 = nullptr;
    lab_ptr head_lab_2 = nullptr;
    lab_ptr head_lab_3 = nullptr;
    lab_ptr head_lab_4 = nullptr;

    set_up_linked_list_for_n_stations(head_lab_1, 5);
    set_up_linked_list_for_n_stations(head_lab_2, 6);
    set_up_linked_list_for_n_stations(head_lab_3, 4);
    set_up_linked_list_for_n_stations(head_lab_4, 3);

    return 0;
}