A special site for solving fun programming problems and challenges, interested in computer science, programming, basics, data structure and algorithms

 reverse linked list using recursion in cpp

Copy
#include<iostream>
using namespace std;

struct node
{
	int data;
	node* next;
};

node* head;

void insert(int value)
{
	node* temp1 = new node();
	temp1->data = value;
	temp1->next = NULL;
	if (head == NULL)
	{
		head = temp1;
		return;
	}
	node* temp2 = head;
	while (temp2->next != NULL)
	{
		temp2 = temp2->next;
	}
	temp2->next = temp1;
}
void print()
{
	node* t = head;
	while (t != NULL)
	{
		cout << t->data << " ";
		t = t->next;
	}
}
void print_reverse(node* p)
{
	if (p->next == NULL)
	{
		head = p;
		return;
	}
	print_reverse(p->next);
	node* temp = p->next;
	temp->next = p;
	p->next = NULL;
}
int main()
{
	insert(1);
	insert(2);
	insert(3);
	insert(4);
	insert(5);
	print();        //list: 1 2 3 4 5.
	cout << endl;
	print_reverse(head);
	print();       //list: 5 4 3 2 1.
	return 0;
}

--------------------------------------------------------------------------------------------
Please support me:
https://www.patreon.com/code12hub

No comments:

Post a Comment