Remove Node from doubly linked list.
Write a Program to delete a new node from the middle of the doubly linked list.
Solution:
using System;
namespace LinkedListOpearation
{
class Program
{
public static void Main()
{
var dList = new DoublyLinkedList();
dList.Add(19);
dList.Add(82);
dList.Add(12);
dList.Add(54);
dList.Add(43);
Console.WriteLine("Doubly Linked List: ");
dList.Print();
dList.DeleteMiddleElement();
Console.WriteLine("After Removing Element from Doubly Linked List: ");
dList.Print();
Console.ReadLine();
}
}
public class DoublyLinkedList
{
public int Size;
public Node Head;
public Node Tail;
public void Add(int data)
{
var newNode = new Node(data);
if (Head == null)
{
Head = Tail = newNode;
Head.Previous = null;
Tail.Next = null;
}
else
{
Tail.Next = newNode;
newNode.Previous = Tail;
Tail = newNode;
Tail.Next = null;
}
Size++;
}
public void DeleteMiddleElement()
{
if (Head == null)
return;
var current = Head;
var mid = (Size % 2 == 0) ? (Size / 2) : ((Size + 1) / 2);
for (var i = 1; i < mid; i++)
{
current = current.Next;
}
if (current == Head)
{
Head = current.Next;
}
else if (current == Tail)
{
Tail = Tail.Previous;
}
else
{
current.Previous.Next = current.Next;
current.Next.Previous = current.Previous;
}
current = null;
Size--;
}
public void Print()
{
var current = Head;
if (Head == null)
return;
while (current != null)
{
Console.WriteLine(current.Data);
current = current.Next;
}
}
}
public class Node
{
public int Data;
public Node Next;
public Node Previous;
public Node(int data)
{
Data = data;
}
}
}