Click here to Skip to main content
15,885,767 members
Articles / Programming Languages / C#

Linked List Implementation in C#

Rate me:
Please Sign up or sign in to vote.
4.37/5 (13 votes)
6 Jun 2016CPOL3 min read 112.1K   14   11
Linked list implementation in C#

In this article, I'll explain about linked list, the pros and cons of using linked list and then implementation of linked list in C#. However, Microsoft provides strongly typed linked list LinkedList(T) in System.Collections.Generic namespace. Here, I'll explain the core implementation of Linked List.

What is Linked List?

Linked list is a linear data structure. It's a collection of elements. Element is called as Node.
Each element has value(data) and reference of next node. The very first node is called as Head and last element has reference to null value.

Types of Linked Lists

Basically, there are 3 types of linked lists.

  1. Singly Linked List: A singly linked list is a list which has a value(data) and a reference to next node. In this, last node's next reference will be null.
  2. Doubly Linked List: A doubly linked list is a list which has a data and 2 references, one for next node and another for previous node and last node's next reference will be null.
  3. Circular Linked List: In circular linked list, last node's next reference will be head or first element. Circular linked list can be singly linked list or doubly linked list.

In this article, I'll explain implementation of only singly linked list.

Pros and Cons

Main advantage of linked list is that it is a dynamic data structure. Unlike in array where length of array is predefined, we can add dynamic number of data in linked list without worrying about size of linked list. So linked list can be used where there is an unknown number of data that needs to be stored at run time.

Disadvantage of linked list is that it takes more space than array. Because it stores reference of next/previous nodes.

Implementation of Linked List

Node Class

Here is the node class which has 2 properties:

C#
public class Node
{
    public Node Next;
    public object Value;
}

One property is 'Next', which will have reference of next node and another is 'Value', which will have data in this node.

LinkedList Class

Now implement linked list class as follows:

C#
public class LinkedList
{
   private Node head;
   private Node current;//This will have latest node
   public int Count;
}

'head' will have head node. 'current' will have latest node, i.e., tail node and 'Count' will return total number of nodes in linked list.

Constructor

Initially, head and current value will be the same and will have empty node, so we will create constructor for that setting.

C#
public LinkedList()
{
  head = new Node();
  current = head;
}

Operations in Linked List

Now, we will create some operations on linked list.

  1. Add node after last element:
    C#
    public void AddAtLast(object data)
    {
       Node newNode = new Node();
       newNode.Value = data;
       current.Next = newNode;
       current = newNode;
       Count++;
    }

    This method will add node after tail node and it will increase count by one. Similarly, you can add node as first node.

  2. Add node as fist element:
    C#
    public void AddAtStart(object data)
    {
      Node newNode = new Node() { Value = data};
      newNode.Next = head.Next;//new node will have reference of head's next reference
      head.Next = newNode;//and now head will refer to new node
      Count++;
    }
    
  3. Remove node from start:
    C#
    public void RemoveFromStart()
    {
       if (Count > 0)
       {
         head.Next = head.Next.Next;
         Count--;
       }
       else
       {
         Console.WriteLine("No element exist in this linked list.");
       }
    }

    Similarly you can write method to remove node from last or from any index. You have to do traverse from head to that particular index and remove node as above by changing the reference.

  4. Traverse whole linked list:
    C#
    /// <summary>
    /// Traverse from head and print all nodes value
    /// </summary>
    
    public void PrintAllNodes()
    {
    //Traverse from head
    Console.Write("Head ->");
    Node curr = head;
    while (curr.Next != null)
    {
    curr = curr.Next;
    Console.Write(curr.Value);
    Console.Write("->");
    }
    Console.Write("NULL");
    }

Start from head and traverse until you get next node as null.

Note: Similarly, you can write code for deleting node of specific index, inserting node on specific position, etc.

Time to Celebrate...

Now it's time to test our code. To test our code, we will write main method and call linked list and its operations in that.

C#
class Program
{
    static void Main(string[] args)
    {           
        LinkedList lnklist = new LinkedList();
        lnklist.PrintAllNodes();
        Console.WriteLine();

        lnklist.AddAtLast(12);
        lnklist.AddAtLast("John");
        lnklist.AddAtLast("Peter");
        lnklist.AddAtLast(34);
        lnklist.PrintAllNodes();
        Console.WriteLine();

        lnklist.AddAtStart(55);
        lnklist.PrintAllNodes();
        Console.WriteLine();

        lnklist.RemoveFromStart();
        lnklist.PrintAllNodes();

        Console.ReadKey();
    }
}

Guess what the output will be. Here it is.

Note: The post first appeared on www.w3techno.blogspot.com.
You can download this project. To download, CLICK HERE.

Did you like this article? Feel free to reach me by leaving comments below.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
India India
Hi I love code and explore coding, thing at machine level.I have 6 years of experience in .net technologies. I have worked on c#,asp.net MVC,EF,Linq,AngularJs,Node js.I do blog at www.w3techno.blogspot.com . When I do't do coding I love to travel and read books.

Comments and Discussions

 
QuestionWhy using 'head.next' during AddAtStart method Pin
Member 1392909030-May-21 12:16
Member 1392909030-May-21 12:16 
QuestionHow to add removeatlast on this program? Pin
Member 141435477-Feb-19 13:52
Member 141435477-Feb-19 13:52 
QuestionHow the Head is updated every time we call the AddLast() function? Pin
Pradeep Kumar Kalsyan22-Nov-17 3:34
Pradeep Kumar Kalsyan22-Nov-17 3:34 
QuestionMy vote of 5! Pin
jediYL9-Jun-16 18:12
professionaljediYL9-Jun-16 18:12 
QuestionWhy are the methods not static? Pin
rhyous8-Jun-16 10:46
rhyous8-Jun-16 10:46 
AnswerRe: Why are the methods not static? Pin
Markus6421-Jun-16 0:42
Markus6421-Jun-16 0:42 
GeneralRe: Why are the methods not static? Pin
rhyous22-Jun-16 9:53
rhyous22-Jun-16 9:53 
QuestionMore differences between a Linked List and an Array Pin
Michael Epner8-Jun-16 1:29
Michael Epner8-Jun-16 1:29 
AnswerRe: More differences between a Linked List and an Array Pin
Ehsan Sajjad19-Mar-17 22:09
professionalEhsan Sajjad19-Mar-17 22:09 
QuestionWhy not generic ? Pin
webmaster4427-Jun-16 19:59
webmaster4427-Jun-16 19:59 
Nice implementation, but in this form it's not very useful. Because you're storing instances of objects, every time you put something in the linked list, the runtime needs to box it, and when you get something out, then it needs to unbox it. This adds a huge unwanted overhead to the program using this implemention. There is a reason why Generics was implemented 10+ years ago in .NET 2.0. So my question: Is there any particular reason not using generics in the implementation?
GeneralMy vote of 3 Pin
Muhammad Shahid Farooq6-Jun-16 21:35
professionalMuhammad Shahid Farooq6-Jun-16 21:35 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.