How to implement Traversal in Singly Linked List using C#?

CsharpProgrammingServer Side Programming

Set a linkelist collection −

var list = new LinkedList<string>();

Now, add elements −

list.AddLast("One");
list.AddLast("Two");
list.AddLast("Four");

Now, let us add new elements in the already created LinkedList −

LinkedListNode<String> node = list.Find("Four");
list.AddBefore(node, "Three");
list.AddAfter(node, "Five");

Let us now see how to traverse through the nodes in a Singly Linked List −

Example

using System;
using System.Collections.Generic;

public class Demo {
   public static void Main(string[] args) {
      var list = new LinkedList < string > ();
      list.AddLast("One");
      list.AddLast("Two");
      list.AddLast("Four");

      Console.WriteLine("Travering...");
      foreach(var res in list) {
         Console.WriteLine(res);
      }

      LinkedListNode < String > node = list.Find("Four");
      list.AddBefore(node, "Three");
      list.AddAfter(node, "Five");

      Console.WriteLine("Travering after adding new elements...");

      foreach(var res in list) {
         Console.WriteLine(res);
      }
   }
}
raja
Published on 31-Aug-2018 09:26:33
Advertisements