Java Program to Insert a New Node at the Beginning of the Circular Linked List
Last Updated :
15 Aug, 2022
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.
Algorithm :
- 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 :
Java
public class AddAtBeginning {
public class Node {
char data;
Node next;
public Node( char data) { this .data = data; }
}
public Node head = null ;
public Node tail = null ;
public void addNode( char data)
{
Node newNode = new Node(data);
if (head == null ) {
head = newNode;
tail = newNode;
tail.next = head;
}
else {
newNode.next = head;
tail.next = newNode;
head = newNode;
}
}
public void printLinkedList()
{
Node presentNode = head;
if (head == null ) {
System.out.println( "List is empty" );
}
else {
System.out.println( "\n" );
do {
System.out.print( " " + presentNode.data);
presentNode = presentNode.next;
} while (presentNode != head);
}
}
public static void main(String[] args)
{
AddAtBeginning obj = new AddAtBeginning();
System.out.println(
"Adding nodes at the beginning of the list: " );
obj.addNode( 's' );
obj.printLinkedList();
obj.addNode( 'k' );
obj.printLinkedList();
obj.addNode( 'e' );
obj.printLinkedList();
obj.addNode( 'e' );
obj.printLinkedList();
obj.addNode( 'G' );
obj.printLinkedList();
}
}
|
Output
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)
Auxiliary space: O(1) as it is using constant space
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...