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

ProgrammingServer Side ProgrammingCsharp

Set a LinkedList and add elements.

string [] students = {"Beth","Jennifer","Amy","Vera"};
LinkedList<string> list = new LinkedList<string>(students);

Firstly, add a new node at the end.

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

Now, use the AddAfter() method to add a node after the given node.

list.AddAfter(newNode, "Matt");

The following is the complete code.

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      string [] students = {"Beth","Jennifer","Amy","Vera"};
      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("Emma");

      // adding a new node after the node added above
      list.AddAfter(newNode, "Matt");

      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var stu in list) {
         Console.WriteLine(stu);
      }
   }
}

Output

Beth
Jennifer
Amy
Vera
LinkedList after adding new nodes...
Beth
Jennifer
Amy
Vera
Emma
Matt
raja
Published on 11-Sep-2018 13:31:01
Advertisements