Linked List

A linked list is a way to store a collection of elements. Like an array these can be character or integers. Each element in a linked list is stored in the form of a node.

A node is a collection of two sub-elements or parts.

  • A data part that stores the element and

  • A next part that stores the link to the next node.

A linked list is formed when many such nodes are linked together to form a chain. Each node points to the next node present in the order. The first node is always used as a reference to traverse the list and is called HEAD. The last node points to NULL.

using System;
using System.Collections.Generic;

public class LinkedListExample {
    public static void Main() {
	string[] words = {"Mon", "Tues", "Wednes", "Thurs", "Fri", "Sat", "Sun"};
	var sentence = new LinkedList<string>(words);
	Display("Items in the LinkedList", sentence);
	
	sentence.AddFirst("Today");
	Display("Insert: At the Beginning", sentence);

	sentence.RemoveFirst();
	Display("Remove: At the Beginning", sentence);
	
	LinkedListNode<string> fnode = sentence.First;
	sentence.RemoveFirst();
	sentence.AddLast(fnode);
	Display("Move First Element to the Last Position", sentence);
	
	sentence.AddLast("Yesterday");
	Display("Insert: At the End", sentence);
	
	sentence.RemoveLast();
	Display("Remove: At the End", sentence);
	
	LinkedListNode<string> lnode = sentence.Last;
	sentence.RemoveLast();
	sentence.AddFirst(lnode);
	Display("Move Last Element to the First Position", sentence);
	
	Console.WriteLine("Contains(): " + sentence.Contains("Today"));
    }
    public static void Display(string message, LinkedList<string> sentence) {
	Console.WriteLine(message);
	foreach (var word in sentence) {
	    Console.Write(word + " ");
	}
	Console.WriteLine("\n");
    }
}

Last updated