DreamsCoder.com

We Code your Dreams


home > Printing the singly linked list in reverse order using recursion in C




Printing the singly linked list in reverse order using recursion in C







Live Demo



Source code







#include 
#include 

struct node
{
    int data;
    struct node *next;
} *temp, *head, *curr;

void ReversePrint(struct node *head);
void RegularPrint(struct node *curr);
void add();

void add()
{
    int num;
    int data, i;
    printf("Enter number of nodes :");
    scanf("%d", &num);
    for (i = 0; i < num; i++)
    {
        temp = (struct node *)malloc(sizeof(struct node));
        printf("Enter the data :");
        scanf("%d", &data);
        temp->data = data;
        if (i == 0)
        {
            head = temp;
            curr = head;
        }
        else
        {
            curr->next = temp;
            curr = temp;
        }
    }
    printf("
RegularPrintlaying in regular order");
    curr = head;
    RegularPrint(curr);
    printf("RegularPrintlaying in reverse order");
    ReversePrint(head);
}

void RegularPrint(struct node *curr)
{
    if (curr == NULL)
        return;
    printf("%d 	", curr->data);
    curr = curr->next;
    RegularPrint(curr);
}

void ReversePrint(struct node *head)
{
    if (head == NULL)
        return;
    ReversePrint(head->next);
    printf("%d 	", head->data);
}

int main()
{
    add();

    return 0;
}

Label - data-structure





by - Chinmay Mahajan





Are you looking for something else?


Suggested Programs




Simple code in C for Binary tree traversal: Preorder, Inorder and Postorder


Singly Link List program in C along with code - [Explained in Video]


Breadth first search in C Language


Program To show whether expression have matching parenthesis or not using C++


Dynamic Queue program using C++