How to save an address?

Mar 8, 2020 at 1:06pm
Hello,
let's say I've got something like this:
1
2
3
4
5
6
7
8
9
10
int main()
{
    numberData* myData = NULL;
    readNumbers(&myData);

    //lots of other things...

    showNumbers(myData);

}

In readNumbers() I load some numbers and save them in a linked-list. When the function returns to main(), let's say I want to print this linked-list with this function:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
void showNumbers(numberData* myData)
{
    if (myData == NULL)
        std::cout << "There are no numbers" << std::endl;
    else
    {
        while (myData->nextNumber != NULL)
        {
            std::cout << myData->thisNumber << std::endl;
            myData = myData->nextNumber;
        }
        std::cout << myData->thisNumber << std::endl;
    }
}

My problem is, when I input those numbers to list in this order:
1
2
3
4

showNumbers() will print:
4
3
2
1

and I need the opposite order. It has to be printed from the first input number to the last.

My idea was to save somewhere address of myData before entering readNumbers(), and when executing showNumbers() function I would pass the address of myData saved before... but I'm not sure if this is the problem.

How to do this? Thanks for any advice
Last edited on Mar 8, 2020 at 1:07pm
Mar 8, 2020 at 1:12pm
Recursion.
Mar 8, 2020 at 2:22pm
Have readNumbers return the root of the list, then pass the root into showNumbers.

Or, make a proper List class that contains the root of the list as a member variable.
Last edited on Mar 8, 2020 at 2:25pm
Mar 8, 2020 at 2:23pm
You could store them in the list in the correct order. When you insert into a linked list, you may choose to insert at the end, or beginning quite easily. Or, you can insert somewhere in the middle, but that involves searching/matching ... and isn't what you need here.

Alternatively, you could use a double threaded linked list, that way you can start from either end when traversing the list.

And, as mentioned above, you can use recursion to get to the end, the print backwards if you have a single threaded linked list.
Mar 8, 2020 at 2:29pm
Thanks for answers.
From all of those I choosed to implement recursion (the easiest way not involving changing much in what I already have) and it works fine
Topic archived. No new replies allowed.