Search code examples
recursionlinked-listnodesreverseiteration

Print singly linked list in reverse order


Okay, this was the bonus question in CMPS 280's test at southeastern Louisiana Univ. Print singly linked list in reverse in three lines. Any ideas?


Solution

  • C implementation of your bonus question, in three lines:

    #include <stdio.h>
    
    struct node {
        int data;
        struct node* next;
    };
    
    void ReversePrint(struct node* head) {
        if(head == NULL) return;
        ReversePrint(head->next);
        printf("%d ", head->data);
    }
    
    int main()
    {
        struct node first;
        struct node second;
        struct node third;
    
        first.data = 1;
        second.data = 2;
        third.data = 3;
    
        first.next = &second;
        second.next = &third;
    
        ReversePrint(&first); // Should print: 3 2 1
        printf("\n");
    
        return 0;
    }