Java Program to Insert a New Node at the Beginning of the Circular Linked List
Circular linked list: A circular linked list is a sequence of elements in which every element points to its next element in the sequence and the last element has a link to the first element. That means a circular linked list is similar to the single linked list except that the last node points to the first node in the list.
Inserting a new node at the beginning of the circular linked list:
If the linked list is empty then both head and tail will point to the newly added node. If the list is not empty, then we will point the last node to newly added node and point the newly added node to head node and finally, we make the newly added node as the head node.
- Create a Node class which represents a node in the list. It has two variables data and next pointer(which points to the next node).
- Create another class for creating the circular linked list and it has two nodes namely head and tail.
- When adding a new node to list then, we will first check whether the head is null. If the list is empty or head is null then we will insert the node as the head, and tail also points to the newly added node.
- If the list is not empty, then the newly added node will point to head, and the tail will point to a newly added node and New node will be made as to the head node.
Code Snippet :
Adding nodes at the beginning of the list: s k s e k s e e k s G e e k s
Time Complexity: O(1)