Remove a node from a doubly linked list

Write a program to Remove a node from a doubly linked list

Solution

using System;

namespace LinkedListOpearation
{
    class Program
    {
        public static void Main()
        {
            var doublyLinkedList = new DoublyLinkedList();

            doublyLinkedList.Add(2);
            doublyLinkedList.Add(4);
            doublyLinkedList.Add(8);
            doublyLinkedList.Add(10);

            Console.WriteLine("Doubly Linked List");
            doublyLinkedList.Print(doublyLinkedList.Head);

            //Delete Element
            doublyLinkedList.DeleteNode(doublyLinkedList.Head, doublyLinkedList.Head);

            Console.WriteLine("List after deleting first node: ");
            doublyLinkedList.Print(doublyLinkedList.Head);

            Console.ReadLine();
        }
    }

    public class DoublyLinkedList
    {
        public Node Head;

        public void Add(int data)
        {
            var node = new Node(data) { Next = Head, Prev = null };

            if (Head != null)
                Head.Prev = node;

            Head = node;
        }

        public void DeleteNode(Node headRef, Node del)
        {
            if (Head == null || del == null)
            {
                return;
            }

            if (Head == del)
            {
                Head = del.Next;
            }

            if (del.Next != null)
            {
                del.Next.Prev = del.Prev;
            }

            if (del.Prev != null)
            {
                del.Prev.Next = del.Next;
            }
        }

        public void Print(Node node)
        {
            while (node != null)
            {
                Console.WriteLine(node.Data);
                node = node.Next;
            }
        }

    }

    public class Node
    {
        public int Data;
        public Node Prev;
        public Node Next;

        public Node(int data)
        {
            Data = data;
        }
    }
}

Leave a Reply

Your email address will not be published. Required fields are marked *