In this post I will show you how to reverse a given linked list in c#.For example a given linked list as show below
10->20->30-NULL
then output should be
30->20->10-NULL
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Algo
{
public class List
{
public List Next { get; set; }
public int Value { get; set; }
public List(int value)
{
Value = value;
}
public override string ToString()
{
List current = this;
StringBuilder builder = new StringBuilder();
while (current!=null)
{
builder.Append(current.Value + "->");
current = current.Next;
}
return builder.ToString();
}
public List ReverseList()
{
List prev = null;
List next = null;
List current = this;
while (current!=null)
{
next = current.Next;
current.Next = prev;
prev = current;
current = next;
}
return prev;
}
}
class Program
{
static void Main(string[] args)
{
List list = new List(10);
list.Next = new List(20);
list.Next.Next = new List(30);
Console.WriteLine(list);
var rev = list.ReverseList();
Console.WriteLine(rev);
}
}
}
Happy Coding 😊