Skip to main content

Reversal order of linked list using recursion in c#

Csharp program for Reversal order of linked list using recursion . Here problem description and explanation.

// Include namespace system
using System;
// Csharp program for
// Print reverse of a linked list without actually reversing

// Linked list node
public class LinkNode
{
	public int data;
	public LinkNode next;
	public LinkNode(int data)
	{
		this.data = data;
		this.next = null;
	}
}
public class SingleLL
{
	public LinkNode head;
	public LinkNode tail;
	public SingleLL()
	{
		this.head = null;
		this.tail = null;
	}
	// Add new Node at end of linked list 
	public void addNode(int data)
	{
		var node = new LinkNode(data);
		if (this.head == null)
		{
			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
	public void printReverse(LinkNode node)
	{
		if (node == null)
		{
			return;
		}
		// Visit to next node
		this.printReverse(node.next);
		// Display node value
		Console.Write(" " + node.data);
	}
	public static void Main(String[] args)
	{
		var 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);
	}
}

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