C# Program to add a node at the first position in a Linked List



Firstly, set a LinkedList with nodes.

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

To add a node at the first position, use the AddFirst() method.

list.AddFirst("Amit");

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
      Console.WriteLine("LinkedList after adding a node at the first position...");
      list.AddFirst("Amit");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}

Output

Tim
Jack
Henry
David
Tom
LinkedList after adding a node at the first position...
Amit
Tim
Jack
Henry
David
Tom

Advertisements