LinkedList Remove method in C#

CsharpProgrammingServer Side Programming

Use the Remove() method to remove the first occurrence of a node in a LinkedList.

Firstly, let us set a LinkedList with integer elements.

int [] num = {2, 5, 7, 15};
LinkedList<int> list = new LinkedList<int>(num);

Now, let’s say you need to remove node with element 7. For that, use the Remove() method.

list.Remove(7);

Let us see the complete code.

Example

 Live Demo

using System;
using System.Collections.Generic;
class Demo {
   static void Main() {
      int [] num = {2, 5, 7, 15};
      LinkedList<int> list = new LinkedList<int>(num);
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // adding a node at the end
      var newNode = list.AddLast(25);
      Console.WriteLine("LinkedList after adding new nodes...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
      // removing
      list.Remove(7);
      Console.WriteLine("LinkedList after removing a node...");
      foreach (var n in list) {
         Console.WriteLine(n);
      }
   }
}

Output

2
5
7
15
LinkedList after adding new nodes...
2
5
7
15
25
LinkedList after removing a node...
2
5
15
25
raja
Updated on 23-Jun-2020 07:47:23

Advertisements