Circular Linked List | Code Tutorial

Circular Linked List is a variation of Linked list in which the first element points to the last element and the last element points to the first element.

public class CircularLinkedList {

	static Node current;
	static Node temp;
	static Node root;
	
	public void addNodes(int data){
		
		Node node = new Node(data);
		
		if(root == null){
			
			root = node;
			//node.nextNode = null;
			//Null changed to root
			root.nextNode = root;
			
		}else{
			
			
			current = root;
			
			//while(current.nextNode!=null){
				
				//current = current.nextNode;
				
			//}
			//while loop checks if next node is root
			while(current.nextNode!=root){
				
				current = current.nextNode;
				
			}
			
			current.nextNode = node;
			//node.nextNode = null;
			node.nextNode = root;
			
		}
		
		
	}
	//No change in insert node
	public void insertNode(int data, int after){
		
		Node node = new Node(data);
		
		int ithNode = 1;
		
		current = root;
		
		while(after != ithNode){
			
			current = current.nextNode;
			ithNode++;
			
		}
		
		temp = current.nextNode;
		current.nextNode = node;
		node.nextNode = temp;
		
		
	}
	
	public void deleteNode(int nodeToBeDeleted){
		
		int ithNode = 1;
		
		current = root;
		
		if(nodeToBeDeleted ==1){
			
			//root = root.nextNode;
			//new delete function for 1
			temp = root.nextNode;
			
			while(temp.nextNode!=root){
				
				temp = temp.nextNode;
				
			}
			
			temp.nextNode = temp.nextNode.nextNode;
			root = current.nextNode;
			
		}else{
			
			while(ithNode != nodeToBeDeleted-1){
				
				current = current.nextNode;
				ithNode++;
				
			}
			
			current.nextNode = current.nextNode.nextNode;
			
		}
		
		//Tell them that this is added in.
		Node.noOfLinkedList--;
		
	}
	
	public void print(){
		
		current = root;
		boolean arrow = false; 
		
		//using the do while loop.
		do{
			
			System.out.print((arrow) ? " --> |" + current.data + "|" : "|" + current.data + "|");
			arrow = true;
			
			current = current.nextNode;
			
		}while(current!=root);
		
	}
	
	public void printCont(){
		
		current = root;
		boolean arrow = true;
		
		for(int i = 0; i < 15; i++){
			
			System.out.print((arrow) ? "|" + current.data + "|" : " --> " + "|" + current.data + "|" );
			
			arrow = false;	
				
			current = current.nextNode;
			
		}
		
	}
	
	public static void main(String[] args){
		
		CircularLinkedList list = new CircularLinkedList ();
		
		list.addNodes(3);
		list.addNodes(7);
		list.addNodes(2);
		list.addNodes(1);
		list.insertNode(4, 4);
		list.deleteNode(5);
		list.printCont();
		
		
	}
	
}


public class Node {

	static int noOfLinkedList = 0;
	
	int data;
	Node nextNode;
	
	Node(int data){
		
		this.data = data;
		noOfLinkedList++;
		
	}
	
}