node=list.Find("Four");list.AddBefore"/> node=list.Find("Four");list.AddBefore">

Home  >  Article  >  Backend Development  >  How to implement traversal of a one-way linked list using C#?

How to implement traversal of a one-way linked list using C#?

PHPz
PHPzforward
2023-08-31 09:41:09938browse

How to implement traversal of a one-way linked list using C#?

Set up the LinkedList collection -

var list = new LinkedList<string>();

Now, add elements-

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

Now, let us add new elements to the already created LinkedList-

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

Now let us see how to traverse 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);
      }
   }
}

The above is the detailed content of How to implement traversal of a one-way linked list using C#?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete