简体   繁体   English

打印出链接列表元素

[英]Printing out linked list elements

I wrote a program that adds elements recursively, and then prints out the elements. 我编写了一个程序,该程序以递归方式添加元素,然后打印出元素。 The problem is, that the program prints out only the first element in the list. 问题是该程序仅打印出列表中的第一个元素。 I tried to solve this, but I don't know where is the problem... 我试图解决这个问题,但我不知道问题出在哪里...

#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();
}

The problem is that after all iterations You have a lot of list objects in which next pointer points to NULL . 问题是,在所有迭代之后,您都有很多列表对象,其中next指针指向NULL You should modify your addNewElement method to something like this: 您应该将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;
}

What had changed? 发生了什么变化? p_list->next pointer is being set to the beginning of next list's element instead of NULL ;) p_list->next指针被设置为下一个列表元素的开头,而不是NULL ;)

EDIT: Here is working code: http://ideone.com/oJ8kX7 编辑:这是工作代码: http : //ideone.com/oJ8kX7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM