LinkedList AddBefore method in C#

CsharpProgrammingServer Side Programming

Add a node before a given node in C# using the AddBefore() method.

Our LinkedList with string nodes.

string [] students = {"Henry","David","Tom"};
LinkedList<string> list = new LinkedList<string>(students);

Now, let’s add node at the end.

// adding a node at the end
var newNode = list.AddLast("Brad");

Use AddBefore() method to add a node before the node added above.

list.AddBefore(newNode, "Emma");

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Henry","David","Tom"};
      LinkedList<string> list = new LinkedList<string>(students);
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
      // adding a node at the end
      var newNode = list.AddLast("Brad");
      // adding a new node before the node added above
      list.AddBefore(newNode, "Emma");
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}

Output

Henry
David
Tom
LinkedList after adding new nodes...
Henry
David
Tom
Emma
Brad
raja
Published on 14-Sep-2018 12:33:26
Advertisements