How do you reverse a singly linked list - recursive method?

This program demonstrates how to reverse a singly linked list recursively.

It uses recursive method to do for doing so.

You can compile this program on bOtskOOl Free Online C/C++ Compiler

#include <stdio.h>
#include <stdlib.h>
struct node {
  int data;
  struct node * next; 
};

struct node * head = NULL;

void insert(int data) {
  struct node * temp = (struct node *)malloc(sizeof(struct node));
  temp->data = data;
  temp->next = head;
  head = temp;
}

void print_LL() {
  struct node * temp = head;
  while(temp!=NULL) {
    printf("%d -> ", temp->data);
    temp = temp->next;            
  }
  printf("NULL\n");
}

struct node * recursive_reverse(struct node * temp) {
  struct node * new_head;
  if(temp->next!=NULL) {
    new_head = recursive_reverse(temp->next);
  }
  else {
    return temp;
  }
  temp->next->next = temp;
  temp->next = NULL;
  return new_head;
}

int main() {
  insert(4);
  insert(41);
  insert(14);
  insert(25);
  insert(3);
  printf("Original Linked List\n");
  print_LL();
  printf("Reversed Linked List\n");
  head = recursive_reverse(head);
  print_LL();
} 

Output

Reverse a singly linked list - recursive method

The above OUTPUT was generated by bOtskOOl Online Compiler - Try it out now>>