LinkedList AddBefore method in C#


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

Updated on: 23-Jun-2020

686 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements