打印出链表元素

时间:2014-03-05 18:08:55

标签: c++ list recursion

我写了一个程序,递归地添加元素,然后打印出元素。问题是,程序只打印出列表中的第一个元素。我试图解决这个问题,但我不知道问题出在哪里......

#include <iostream>

using namespace std;

struct list
{
    int value;
    list* next;
};

list* addNewElement(list* p_head, int elems)
{
    if (elems >= 1)
    {
        list* p_list = new list;

        cout << "Enter a value: ";
        cin >> p_list->value;

        p_list->next = p_head;

        addNewElement(p_head, elems - 1);

        return p_list;
    }
}

void printList(list* p_head)
{
    list* p_cur = p_head;

    cout << "ELEMENTS: " << endl;

    while (p_cur != NULL)
    {
        cout << p_cur->value;
        p_cur = p_cur->next;
    }

    cout << endl;
}

int main()
{
    list* p_head = NULL;

    int elemNR;

    cout << "Enter how many elements do you want in the list: ";
    cin >> elemNR;

    p_head = addNewElement(p_head, elemNR);

    cout << endl;

    printList(p_head);

    cout << endl;

    cout << "PRESS <ENTER> TO CONTINUE...";

    cin.ignore();
    cin.get();
}

1 个答案:

答案 0 :(得分:3)

问题是在所有迭代之后你有很多列表对象,其中next指针指向NULL。您应该将addNewElement方法修改为以下内容:

list* addNewElement(list* p_head, int elems) {
    if (elems >= 1) {
        list* p_list = new list;

        cout << "Enter a value: ";
        cin >> p_list->value;

        p_list->next = addNewElement(p_head, elems - 1);
        return p_list;
    }
    return p_head;
}

发生了什么变化? p_list->next指针被设置为下一个列表元素的开头,而不是NULL;)

编辑:这是工作代码:http://ideone.com/oJ8kX7