# Sorted Insert for Circular Linked List ## JAVA Program to Sort a Circular Linked List while Inserting Nodes in it

As we’ve learned in the earlier pages that Insertion can be done at various Positions in a Circular Linked List. In this page we’ll learn how we can use those techniques to create program using which we can insert nodes in a Circular Linked List and Sort the list Simultaneously. Below is a Solution in the form of a JAVA Program for Sorted Insert for Circular Linked List along with a detailed analysis of example.

## Algorithm that will be used in the Program below

• sortedInsert(Node nextNode)
• IF thisNode == null
• nextNode->next = nextNode
• ELSE IF (thisNode->element >= nextNode->element)
• FOR i=0 until thisNode->next != head
• thisNode = thisNode->next
• thisNode->next = nextNode
• ELSE
• WHILE thisNode->next != head && thisNode->next->element < nextNode-> element
• thisNode = thisNode->next
• nextNode->next = thisNode->next
• thisNode->next = nextNode
• EXIT

## Code in JAVA Programming Language

Run
```import java.util.*;
public class Main
{
Main()
{
}
void sortedInsert(Node nextNode)
{
if (thisNode == null)
{
nextNode.next = nextNode;
}
else if (thisNode.element >= nextNode.element)
{
for (int i=0; thisNode.next != head; i++)
thisNode = thisNode.next;
thisNode.next = nextNode;
}
else
{
while (thisNode.next != head && thisNode.next.element < nextNode.element)
thisNode = thisNode.next;
nextNode.next = thisNode.next;
thisNode.next = nextNode;
}
}
public void print() {
System.out.println("null");
}
else {
do{
System.out.print(temp.element+ " ");
temp = temp.next;
System.out.println();
}
}
public static void main(String[] args)
{
Main ll = new Main();
Scanner s = new Scanner(System.in);
Node temp = null;
System.out.println("Enter 6 elements of the Circular Linked List");
for (int i = 0; i < 6; i++)
{
temp = new Node(s.nextInt());
ll.sortedInsert(temp);
}
ll.print();
}
}
class Node
{
int element;
Node next;
Node(int e)
{
element = e;
next = null;
}
}

```
```Enter 6 elements of the Circular Linked List
1
4
6
3
2
3