How to reverse a linked list in C#

In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence
LinkedIn is a popular topic for coding interviews. There are many classic interview questions, such as "find the middle of a given linked list," "detect the loop in a linked list," and "reverse a linked list." The term "reverse" refers to the node rather than the data. I'll show you how to reverse a linked list in C# in this blog post.
You will have learned the following by the end of this tutorial:
  • What exactly is a linked list?
  • Inserting data into a linked list
  • How to reverse a linked list in C#

Lets consider the following linked list

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 😊


Please do not post any spam link in the comment box😊

Post a Comment (0)
Previous Post Next Post