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 -
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!