C# Program to add a node before the given node in a Linked List


Declare a LinkedList and add nodes to it.

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

Let us add a new node.

var newNode = list.AddLast("Kevin");

Now, to add a node before the given node, use the AddBefore() method.

list.AddBefore(newNode, "Matt");

Let us now see the complete code.

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Tim","Jack","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("Kevin");
      // adding a new node before the node added above
      list.AddBefore(newNode, "Matt");
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}

Output

Tim
Jack
Henry
David
Tom
LinkedList after adding new nodes...
Tim
Jack
Henry
David
Tom
Matt
Kevin

Updated on: 23-Jun-2020

173 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements