Delete nth element from headnode using C#


Firstly, set a link list and add some elements.

Demo list = new Demo();
list.Push(50);
list.Push(100);
list.Push(150);

Now to delete nth element from headnode, pass what you want to delete. If you will set 1, then it will delete the head node.

Example

if (val == 1) {
   head = head.Next;
   return;
}
// n points to the node before the node we wish to delete
Node n = head;
// m is the node set to be deleted
Node m = head.Next;
for (int i = 2; i < val; i++) {
   n = n.Next;
   m = m.Next;
}
n.Next = m.Next;

Above, we have set the following to point the node before the node we want to delete.

Node n = head;

Updated on: 23-Jun-2020

92 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements