Write a function to delete a Linked List in C#

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 sequenc

In this article, I will show you how to delete nodes from LinkedList. The Algorithm for deleting the node from LinkedList is shown below

Algorithm

While i<index-1
    pre=prev.Next
nodeToDeleted=prev.next;
prev.next=nodeToDeleted.next
  • Set prev pointer to head
  • 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;

	}

}
Next Post Previous Post
No Comment
Add Comment
comment url