C# program to print a singly linked list backwards using recursion
Here's a C# program that prints a singly linked list backwards using recursion:
using System;
class Node
{
public int Data;
public Node Next;
public Node(int data)
{
Data = data;
Next = null;
}
}
class LinkedList
{
private Node Head;
public LinkedList()
{
Head = null;
}
public void AddNode(int data)
{
Node newNode = new Node(data);
if (Head == null)
{
Head = newNode;
}
else
{
Node current = Head;
while (current.Next != null)
{
current = current.Next;
}
current.Next = newNode;
}
}
public void Display()
{
DisplayBackwards(Head);
}
private void DisplayBackwards(Node node)
{
if (node == null)
{
return;
}
// Recursive call to print the next node in reverse
DisplayBackwards(node.Next);
// Print the current node's data
Console.Write(node.Data + " ");
}
}
class Program
{
static void Main()
{
LinkedList linkedList = new LinkedList();
linkedList.AddNode(1);
linkedList.AddNode(2);
linkedList.AddNode(3);
linkedList.AddNode(4);
linkedList.AddNode(5);
Console.WriteLine("Singly Linked List (Backwards):");
linkedList.Display();
}
}
In this program, we have the Node class representing a node in the singly linked list. Each node contains an integer Data and a reference to the next node Next.
The LinkedList class manages the linked list and provides methods to add nodes to the list and display the list backwards.
The AddNode method adds a new node with the given data to the end of the linked list.
The Display method is the entry point to print the linked list backwards. It calls the DisplayBackwards method with the Head node as the starting point.
The DisplayBackwards method is a recursive method that prints the linked list in reverse order. It takes a Node parameter, representing the current node to be printed. The method first makes a recursive call to DisplayBackwards with the next node in the list. This recursive call effectively traverses the list in reverse order. After the recursive call, it prints the data of the current node.
The Main method initializes a new linked list, adds nodes to it, and then calls the Display method to print the linked list backwards.
In the example above, the output would be:
Singly Linked List (Backwards):
5 4 3 2 1
The singly linked list 1 -> 2 -> 3 -> 4 -> 5 is printed in reverse order as 5 4 3 2 1.