19. Deletion from a circular linked list

19. Deletion from a circular linked list


Problem link :- click here


package Linked_List;

public class LinkedList__19
{

	static void deleteFromCircular(LinkedList list, int data)
	{
		if(list.head.data == data)
		{
			Node last = list.head;
			while(last.next != list.head)
				last = last.next;
			
			last.next = list.head.next;
			list.head = list.head.next;
		}
		
		Node head = list.head;
		
		Node cur = list.head.next;
		Node prev = list.head;
		for(cur=list.head.next; cur!=head; cur=cur.next)
		{
			if(cur.data == data)
				prev.next = cur.next;
			else
				prev = cur;
		}
	}
	
	public static void main(String[] args)
	{
		LinkedList list = new LinkedList();
		list.push(2);
		list.push(5);
		list.push(7);
		list.push(8);
		list.push(10);
		
		//making the list circular
		list.head.next.next.next.next.next = list.head;
		
		System.out.println("Linked brfore deleting any node : ");
		printList(list);
		
		deleteFromCircular(list, 10);
		System.out.println("Linked list after deleting the node : ");
		printList(list);
	}

	static void printList(LinkedList list)
	{
		int n = list.size();
		Node temp=list.head;
		for(int i=0; i<n; i++)
		{
			System.out.print(temp.data + "-> ");
			temp=temp.next;
		}
		System.out.println();
	}
}

Time complexity :- O(n)
Space complexity :- O(1)

Comments

Popular posts from this blog

4.Sort an array of 0's, 1's & 2's.

1. Reverse

3. Height of Binary tree