In computer science, a linked list is a linear collection of data elements whose order is not given by their physical placement in memory. Instead, each element points to the next. It is a data structure consisting of a collection of nodes which together represent a sequence
In this article, I will show you how to delete nodes from Linked List. The question can be asked in several ways like delete a node from given linked list or delete a linked list node at specific position in c#.The Algorithm for deleting the node from the linked list is shown below
Algorithm
While i<index-1
pre=prev.Next
nodeToDeleted=prev.next;
prev.next=nodeToDeleted.next
- Set
prev
pointer tohead
- Loop till
position-1
- Get the next node from the
prev
- Set the
prev
next to a node to be deleted node.
]
void Main()
{
var linkedList = new LinkedList();
linkedList.Insert(1);
linkedList.Insert(3);
linkedList.Insert(5);
linkedList.Insert(6);
Console.WriteLine(linkedList);
linkedList.RemoveNode(2);
Console.WriteLine(linkedList);
}
public class LinkedList
{
private class Node
{
public int Data { get; set; }
public Node Next { get; set; }
public Node(int data)
{
Data = data;
Next = null;
}
}
private Node _head;
public void Insert(int data)
{
var newNode = new Node(data);
if (_head == null)
{
_head = newNode;
return;
}
else
{
newNode.Next = _head;
_head = newNode;
}
}
// To Print the string
public override string ToString()
{
Node current = _head;
var builder = new StringBuilder();
while (current != null)
{
builder.Append(current.Data + "->");
current = current.Next;
}
builder.Append("NULL");
return builder.ToString();
}
public void RemoveNode(int index)
{
//If LL is empty do nothing
if (_head == null)
return;
if (index == 0)
_head = _head.Next;
var prev = _head;
for (int i = 1; i < index - 1; i++)
{
prev = prev.Next;
}
var nodeToBeDeleted = prev.Next;
prev.Next = nodeToBeDeleted.Next;
}
}