Our Feeds

Sunday, 8 November 2015

AJITH KP

Reverse Singly Linked List (SLL) using Recursion

Hi GuyZ,
     This is another question which you have to attend in Data Structures and Algorithms paper in BCA/MCA/B.Tech. The solution for this problem is very simple and efficient than solve the same problem using `stack` data structure.


Source Code


#include <iostream>
using namespace std;
/*
 * 
 * Coded By Ajith Kp [ ajithkp560 ]
 * [ http://www.terminalcoders.blogspot.com ]
 * 
 * /
struct list
{
 int data;
 list *link;
} *root;
void rev(list *n)
{
 if(n==NULL)return;
 rev(n->link);
 cout<<n->data<<" ";
 
}
int main()
{
 int i, data, num;
 list *tmp, *n;
 n = new list;
 root = NULL;
 cout<<"Enter the number of elements in the list: ";
 cin>>num;
 cout<<"Enter "<<num<<" integers: ";
 cin>>n->data;
 n->link = NULL;
 root = n;
 tmp = root;
 for(i=0;i<num-1;i++)
 {
  n = new list;
  cin>>n->data;
  n->link = NULL;
  tmp->link = n;
  tmp = n;
 }
 tmp = root;
 rev(tmp);
 cout<<endl;
 return 0;
}