Delete middle node from linked list in csharp

Csharp program for Delete middle node from linked list. Here problem description and explanation.

// Include namespace system
using System;
/*
    Csharp program for
    Delete middle node of linked list
*/
// Linked list node
public class LinkNode
{
	public int data;
	public LinkNode next;
	public LinkNode(int data)
	{
		this.data = data;
		this.next = null;
	}
}
public class SingleLL
{
	public LinkNode head;
	public SingleLL()
	{
		this.head = null;
	}
	// Adding new node at beginning of linked list
	public void addNode(int data)
	{
		// Create new node
		var node = new LinkNode(data);
		// Connect current node to previous head
		node.next = this.head;
		this.head = node;
	}
	// Display linked list element
	public void display()
	{
		if (this.head == null)
		{
			return;
		}
		var temp = this.head;
		// iterating linked list elements
		while (temp != null)
		{
			// Display node value
			Console.Write(temp.data + " → ");
			// Visit to next node
			temp = temp.next;
		}
		Console.Write(" NULL\n");
	}
	// Delete the middle node of linked list
	public void deleteMid()
	{
		if (this.head == null)
		{
			// When linked list are no elements
			Console.WriteLine("Empty Linked List");
		}
		else if (this.head.next == null && 
                 this.head.next.next == null)
		{
			// When linked list are less than  of 3 nodes
			Console.WriteLine("Less then 3 node of linked list");
		}
		else
		{
			var temp = this.head;
			LinkNode midPrevious = null;
			// Find the middle and its previous node
			while (temp != null && 
                   temp.next != null && 
                   temp.next.next != null)
			{
				if (midPrevious == null)
				{
					// When first node
					midPrevious = temp;
				}
				else
				{
					// Visit to next node
					midPrevious = midPrevious.next;
				}
				// Visit to next second next node
				temp = temp.next.next;
			}
			// Get the node which is deleting 
			temp = midPrevious.next;
			// Show deleted node
			Console.WriteLine("Delete node : " + temp.data);
			// Change link
			midPrevious.next = temp.next;
		}
	}
	public static void Main(String[] args)
	{
		var sll = new SingleLL();
		// Linked list
		// 7 → 6 → 5 → 4 → 3 → 2 → 1 → NULL
		sll.addNode(1);
		sll.addNode(2);
		sll.addNode(3);
		sll.addNode(4);
		sll.addNode(5);
		sll.addNode(6);
		sll.addNode(7);
		Console.WriteLine("Before Delete middle node");
		sll.display();
		// Delete middle node
		sll.deleteMid();
		Console.WriteLine("After Delete middle node");
		sll.display();
	}
}

Output

Before Delete middle node
7 → 6 → 5 → 4 → 3 → 2 → 1 →  NULL
Delete node : 4
After Delete middle node
7 → 6 → 5 → 3 → 2 → 1 →  NULL


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved