0

could someone please show me how i would be able to reverse the printout of a linked list?, i have gotten it to print out in the right order but not sure how to make to printout in reverse.

here is my current code,

void print(node*& head)
{
	node* temp;

	temp = head;

	while (temp != NULL)
	{
		cout << temp->base;
		temp = temp->next;
	}
}

at the moment the print function prints out whats in the linked list in the correct order, i want it to do it in reverse, please help

3
Contributors
4
Replies
5
Views
8 Years
Discussion Span
Last Post by opposition
0

Your nodes don't have a link 'previous' (singly-linked), so as far as I can see, you'll have to store all the data in some sort of container (a vector for example, or another linked list :P ) and print that out in reverse order.

2

To reverse the printout of the linked list you can try something like the following:

void print(node*& head)
{
    node * temp = head;
    if (temp->next != null)
    {
        print(temp->next);
    }

    cout << temp->base; 
}

This way you first recursively go to the last element of the linked list, and then start printing from back to the first element.

This is just theoretical though. I don't know (and don't have the tools present) if it will work in practice.

Votes + Comments
Nice work
Good correction! m.v.g. Niek
0

Thanks for the replys, I tried miepmuts method and it works great, didnt think of doing it that way lol

+rep :)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.