LinkedList AddFirst method in C#


In a Linked List, if you want to add a node at the first position, use AddFirst method.

Let’s first set a LinkedList.

string [] students = {"Jenifer","Angelina","Vera"};
LinkedList<string> list = new LinkedList<string>(students);

Now, to add an element as a first node, use AddFirst() method.

List.AddFirst(“Natalie”);

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Jenifer","Angelina","Vera"};
      LinkedList<string> list = new LinkedList<string>(students);
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
      // add a node
      Console.WriteLine("Node added at the first position...");
      list.AddFirst("Natalie");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}

Output

Jenifer
Angelina
Vera
Node added at the first position...
Natalie
Jenifer
Angelina
Vera

Updated on: 23-Jun-2020

518 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements