Linked List Reverse Print

This code is in C; the only major difference between it and C++ are in the way that structs are declared; in C++, "node* next" is sufficient. It would, of course, be possible to replace the printf with cout if so desired.

#include <stdio.h>

struct node
    int val;
    struct node* next;

void print_reverse( struct node* list )
    if ( list != 0 )
        print_reverse( list->next );
        printf( "%d\n", list->val );
This solution uses recursion to reverse the linked list by, in effect, placing every element on the list on the call stack. Since the first element put on a stack is the last one removed, by putting the list on the stack in order, we can remove the elements in exactly the reverse order.

Other solutions that do not use recursion would need to explicitly handle the stack, perhaps by constructing a linked list in reverse order.

Download source