This code allows you to create a linked list and reverse it recursively.
Reversing a linked list - recursively.
/***********list.h***************************/
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
typedef class _node
{
public:
int datum;
_node *next;
_node *prev;
}node;
class linkedlist
{
public:
node* CreateList(int num,node*);
node* Reverse(node* nd);
node* n;
};
/******************list.cpp******************/
#ifndef LIST_H
#define LIST_H
#include "list.h"
// Create a random list of elements
node* linkedlist::CreateList(int num,node* List)
{
node *firstEle = NULL;
firstEle = new node();
firstEle->datum = 1;
firstEle->next = NULL;
List = firstEle;
for(int i =1; i<num; i++)
{
firstEle->next = new node();
firstEle->next->datum = i+1+ pow((-i),(i+1));
firstEle->next->next = NULL;
firstEle = firstEle->next;
}
return List;
}
void linkedlist::PrintList(node *nd)
{
printf("Printing the List\n");
while(nd!= NULL)
{
printf("%d\t",nd->datum);
nd = nd->next;
}
printf("\n");
}
node* linkedlist::Reverse(node*p)
{
node* rev;
static node* tail = NULL;
static int count =0;
if(p->next)
{
count++;
// Use the static variable to return once all the elements of
// the list are reversed.
rev = Reverse(p->next);
count--;
rev->next = p; // Construct the reversed list.
rev->next->next = NULL;
if(count == 0)
return tail;
else
return rev->next;
}
else
{
tail = p; // store the pointer to the tail element
tail->next = NULL;
return tail;
}
}
#endif
/*******************main.cpp*********************/
#ifndef LIST_H
#include "list.h"
main()
{
linkedlist *llist = new linkedlist();
node* nd = llist->CreateList(3,llist->n);
llist->PrintList(nd);
nd = llist->Reverse(llist->n);
llist->PrintList(nd);
return 0;
}
#endif
ChaseVoid 30 Junior Poster
wael.salman 0 Newbie Poster
mstorch 0 Newbie Poster
Haranadh 0 Newbie Poster
Haranadh 0 Newbie Poster
danifar 0 Newbie Poster
xXFireBladeXx 0 Newbie Poster
dios 0 Newbie Poster
arshdeepkaur 0 Newbie Poster
Prad_1 0 Newbie Poster
Be a part of the DaniWeb community
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.