Recursion

a
Last edited on
a
Last edited on
It seems that your list is a single linked list. If so you can not print it in the reverse order.
a
Last edited on
You should show definition of Node<T>.

As I have said already it seems that you defined single linked list. That is each Node has a reference to a next element but has no reference to a previos element. As it seen from your code there is member next of type Node<T> but I do not see something as member prev. Without a reference to the previous element in a given position inside your list it is impossible to print list in reverse order.
Last edited on
a
Last edited on
a
Last edited on
I still can't get anything other than the data in the tail to output... any ideas?
As I have already explained you cannot print your list iin reverse order because each node in your list knows nothing about its previous node. You can travers your list only in one direction.
You should define a double linled list that to be able to print its element in reverse order.
Last edited on
You can print a singly linked list in reverse order using recursion.

Hint: You can get it to work by making a minor modification to your listContents function (you can pass in the head as usual). Think of where you print the node's data.

1
2
3
4
5
6
7
8
9
10
11
12
13
//make a minor modification to this function to print
//the singly linked list in reverse order. Think of where
//you print the node's data.
template< typename T >	                    
void LinkedList<T>::listReverseContents(Node<T> * head)
{
   if (head == NULL)  return;
   else
   {
      cout <<  head->data  << "  ->  ";
      listContents( head -> next );
   }
}
Last edited on

shacktar ,

I did not take into account recursion because I thought that this is not effective. You are right that using recursion the list can be printed.
Ahhh I know im soo close! Could you give me a little additional help. I've tried every minor change I can think ahah!
a
Last edited on
a
Last edited on
It is simple.

1
2
3
4
5
6
7
8
template< typename T >	                    
void LinkedList<T>::listReverseContents(Node<T> * head)
{
   if (head == NULL)  return;

   listReverseContents( head -> next );
   cout <<  head->data  << "  ->  ";
}
Last edited on
That solution does work I assure you. I am working this right now!

You are all very helpful!

Now i get onto the next problem.

Thanks again!
Last edited on
Topic archived. No new replies allowed.