Skip to main content

Print reverse view of linked list using recursion in c++

C++ program for Print reverse view of linked list using recursion. Here more information.

// Include header file
#include <iostream>
using namespace std;
// C++ program for
// Print reverse of a linked list without actually reversing

// Linked list node
class LinkNode
{
	public: int data;
	LinkNode *next;
	LinkNode(int data)
	{
		this->data = data;
		this->next = nullptr;
	}
};
class SingleLL
{
	public: 
    LinkNode *head;
	LinkNode *tail;
	SingleLL()
	{
		this->head = nullptr;
		this->tail = nullptr;
	}
	// Add new Node at end of linked list 
	void addNode(int data)
	{
		LinkNode *node = new LinkNode(data);
		if (this->head == nullptr)
		{
			this->head = node;
		}
		else
		{
			// Append the node at last position
			this->tail->next = node;
		}
		this->tail = node;
	}
	// Display reversal view of linked list using recursion
	void printReverse(LinkNode *node)
	{
		if (node == nullptr)
		{
			return;
		}
		// Visit to next node
		this->printReverse(node->next);
		// Display node value
		cout << " " << node->data;
	}
};
int main()
{
	SingleLL *sll = new SingleLL();
	//  1 → 2 → 8 → 4 → 9 → 6 → NULL
	sll->addNode(1);
	sll->addNode(2);
	sll->addNode(8);
	sll->addNode(4);
	sll->addNode(9);
	sll->addNode(6);
	// Reversal view
	// 6 9 4 8 2 1
	sll->printReverse(sll->head);
	return 0;
}

Output

 6 9 4 8 2 1




Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment