# Insert into a Sorted Circular Linked List in C++

C++Server Side ProgrammingProgramming

Suppose we have a node from a Circular Linked List which is sorted in increasing order, we have to define a function to insert a value insertVal into the list such that it remains a sorted circular list.

The node can be a reference to any single node in the list, and may not be necessarily the first value of the circular list. If there are multiple suitable places for insertion, we can choose any place to insert the new value. If the list is empty, then we have to create a new single circular list and return the reference to that single node. Otherwise, we should return the original given node.

So, if the input is like head = [3,4,1], insertVal = 2, image, then the output will be [3,4,1,2], image

To solve this, we will follow these steps −

• if head is null, then −

• head := new node with val

• Otherwise

• curr = next of head

• temp = new node with val

• done := false

• Do infinite looping, do −

• if val in curr >= val and val of prev <= val, then −

• prev := next of temp

• temp := next of curr

• done := true

• Come out from the loop

• if val of prev > val of curr, then −

• if val of prev <= val or val <= val of curr, then −

• prev := next of temp

• temp := next of curr

• done := true

• Come out from the loop

• if curr is same as head, then −

• Come out from the loop

• prev := curr

• curr := next of curr

• if done is false, then −

• temp := next of head

• prev := next of temp

## Example

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class Node {
public:
int val;
Node* next;
Node() {}
Node(int _val) {
val = _val;
next = NULL;
}
Node(int _val, Node* _next) {
val = _val;
next = _next;
}
};
class Solution {
public:
Node* insert(Node* head, int val) {
}
else{
Node* temp = new Node(val);
bool done = false;
while(1){
if (curr->val >= val && prev->val <= val) {
prev->next = temp;
temp->next = curr;
done = true;
break;
}
if (prev->val > curr->val) {
if (prev->val <= val || val <= curr->val) {
prev->next = temp;
temp->next = curr;
done = true;
break;
}
}
break;
prev = curr;
curr = curr->next;
}
if(!done){
prev->next = temp;
}
}
}
};
main(){
Solution ob;
do{
cout << temp->val << " ";
temp = temp->next;
}
}
}

## Input

node *head = new Node(3);
insertVal = 2
3 4 1 2