C# program to reverse a Linkedlist
Here's an example of a C# program that demonstrates how to reverse a built-in LinkedList in C#. It includes the implementation of the reverse method, along with an example usage that creates a LinkedList, adds elements to it, reverses the list, and then displays its contents.
using System;
using System.Collections.Generic;
class Program
{
static void Main(string[] args)
{
// Create a LinkedList and add elements
LinkedList linkedList = new LinkedList();
linkedList.AddLast(1);
linkedList.AddLast(2);
linkedList.AddLast(3);
linkedList.AddLast(4);
linkedList.AddLast(5);
// Display the original list
Console.WriteLine("Original List:");
foreach (var item in linkedList)
{
Console.Write(item + " ");
}
Console.WriteLine();
// Reverse the list
ReverseLinkedList(linkedList);
// Display the reversed list
Console.WriteLine("Reversed List:");
foreach (var item in linkedList)
{
Console.Write(item + " ");
}
Console.WriteLine();
}
static void ReverseLinkedList(LinkedList list)
{
LinkedListNode current = list.First;
LinkedListNode previous = null;
while (current != null)
{
LinkedListNode next = current.Next;
current.Next = previous;
previous = current;
current = next;
}
list.First = previous;
}
}
Output:
Original List:
1 2 3 4 5
Reversed List:
5 4 3 2 1
In this example, we use the built-in LinkedList class in C# to represent the linked list. We create a LinkedList and add elements to it using the AddLast method.
The ReverseLinkedList method takes a LinkedList as input and reverses the order of its elements. It uses three pointers: current, previous, and next. The current pointer starts at the first node, and while it's not null, we update the next pointer to point to the next node, reverse the next pointer of the current node to point to the previous node, and move the previous and current pointers to the next positions. We repeat this process until we reach the end of the list. Finally, we update the First property of the LinkedList to point to the last node, effectively reversing the list.
In the Main method, we create a LinkedList, add elements to it, display the original list, call the ReverseLinkedList method to reverse it, and then display the reversed list using a foreach loop.