Delete node from Circular Linked List

Write a Program to delete a new node from the end of the circular linked list.

Solution:

using System;

namespace LinkedListOpearation
{
    class Program
    {
        public static void Main()
        {
            var linkedList = new LinkedList();
            linkedList.Add(6);
            linkedList.Add(1);
            linkedList.Add(5);
            linkedList.Add(1);
            linkedList.Add(3);
            linkedList.Add(9);
            Console.WriteLine($"Circular Linked List");
            linkedList.Print();
            linkedList.DeleteEnd();
            Console.WriteLine($"After Deleting Last elements from Circular Linked List");
            linkedList.Print();
            Console.ReadLine();
        }
    }


    public class LinkedList
    {
        public Node Head;
        public Node Tail;
        public void Add(int data)
        {
            Node newNode = new Node(data);

            if (Head == null)
            {
                Head = newNode;
                Tail = newNode;
                newNode.Next = Head;
            }
            else
            {
                Tail.Next = newNode;
                Tail = newNode;
                Tail.Next = Head;
            }
        }

        public void Print()
        {
            Node current = Head;
            if (Head == null)
                return;

            do
            {
                Console.WriteLine(current.Data);
                current = current.Next;
            } while (current != Head);
        }

        public void DeleteEnd()
        {
            if (Head == null)
            {
                return;
            }

            if (Head != Tail)
            {
                Node current = Head;
                while (current.Next != Tail)
                {
                    current = current.Next;
                }
                Tail = current;
                Tail.Next = Head;
            }
            else
            {
                Head = Tail = null;
            }
        }

    }

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

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

Leave a Reply

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