Friday, July 11, 2014

Printing out a linked list in reverse using recursion

Define the class for the linked list node:
class LinkedList {
public:
    int value;
    LinkedList *next;
};

populate the linked list:
void populate(int N)
{
    top = ll;
    for (int i=0 ; i< N; ++i)
    {
      ll->value = i;
      cout << ll->value;
      if( i!=N-1 ) {
        ll->next = new LinkedList;
        ll = ll->next;
     }
      else ll->next = (LinkedList *)0;
    }
    ll=top;
}

Print it out:
void print_ll()
{
    while(ll != (LinkedList *)0 ){
        cout << ll->value;
        ll = ll->next;
    }
    cout << endl;
    ll = top;
}

Reverse it:
void reverse_ll(LinkedList *node)
{
 
    if( node->next != (LinkedList *)0 ) {
        reverse_ll(node->next);
    }
    cout << node->value;
}

Please leave comments.

Thank you,
Christopher

No comments: