Using LinkedList from System.Collections.Generic - CSharp Collection

CSharp examples for Collection:LinkedList

Description

Using LinkedList from System.Collections.Generic

Demo Code

using System;// w  w w  .j av  a  2  s.  c om
using System.Collections.Generic;
class LinkedListTest
{
   private static readonly string[] colors = {"black", "yellow", "green", "blue", "violet", "silver"};
   private static readonly string[] colors2 = {"gold", "white", "brown", "blue", "gray"};
   static void Main()
   {
      var list1 = new LinkedList<string>();
      foreach (var color in colors){
         list1.AddLast(color);
      }
      var list2 = new LinkedList<string>(colors2);
      Concatenate(list1, list2); // concatenate list2 onto list1
      PrintList(list1); // display list1 elements
      Console.WriteLine("\nConverting strings in list1 to uppercase\n");
      ToUppercaseStrings(list1); // convert to uppercase string
      PrintList(list1); // display list1 elements
      Console.WriteLine("\nDeleting strings between BLACK and BROWN\n");
      RemoveItemsBetween(list1, "BLACK", "BROWN");
      PrintList(list1); // display list1 elements
      PrintReversedList(list1); // display list in reverse order
   }
   private static void PrintList<T>(LinkedList<T> list)
   {
      Console.WriteLine("Linked list: ");
      foreach (var value in list)
      {
         Console.Write($"{value} ");
      }
      Console.WriteLine();
   }
   private static void Concatenate<T>(LinkedList<T> list1, LinkedList<T> list2)
   {
      foreach (var value in list2){
         list1.AddLast(value); // add new node
      }
   }
   private static void ToUppercaseStrings(LinkedList<string> list)
   {
      LinkedListNode<string> currentNode = list.First;
      while (currentNode != null){
         string color = currentNode.Value; // get value in node
         currentNode.Value = color.ToUpper(); // convert to uppercase
         currentNode = currentNode.Next; // get next node
      }
   }
   private static void RemoveItemsBetween<T>(LinkedList<T> list, T startItem, T endItem)
   {
      LinkedListNode<T> currentNode = list.Find(startItem);
      LinkedListNode<T> endNode = list.Find(endItem);
      while ((currentNode.Next != null) && (currentNode.Next != endNode))
      {
         list.Remove(currentNode.Next); // remove next node
      }
   }
   private static void PrintReversedList<T>(LinkedList<T> list)
   {
      Console.WriteLine("Reversed List:");
      // iterate over the list by using the nodes
      LinkedListNode<T> currentNode = list.Last;
      while (currentNode != null)
      {
         Console.Write($"{currentNode.Value} ");
         currentNode = currentNode.Previous; // get previous node
      }
      Console.WriteLine();
   }
}

Result


Related Tutorials