# Sorted insert for circular linked list

Difficulty Level: Rookie
Write a C function to insert a new value in a sorted Circular Linked List (CLL). For example, if the input CLL is following.

After insertion of 7, the above CLL should be changed to following

## Recommended: Please solve it on “PRACTICE” first, before moving on to the solution.

Algorithm:
Allocate memory for the newly inserted node and put data in the newly allocated node. Let the pointer to the new node be new_node. After memory allocation, following are the three cases that need to be handled.

```1) Linked List is empty:
a)  since new_node is the only node in CLL, make a self loop.
new_node->next = new_node;
b) change the head pointer to point to new node.
2) New node is to be inserted just before the head node:
(a) Find out the last node using a loop.
current = current->next;
(b) Change the next of last node.
current->next = new_node;
(c) Change next of new node to point to head.
(d) change the head pointer to point to new node.
3) New node is to be  inserted somewhere after the head:
(a) Locate the node after which new node is to be inserted.
current->next->data < new_node->data)
{   current = current->next;   }
(b) Make next of new_node as next of the located pointer
new_node->next = current->next;
(c) Change the next of the located pointer
current->next = new_node;
```

## C

```#include<stdio.h>
#include<stdlib.h>

/* structure for a node */
struct Node
{
int data;
struct Node *next;
};

/* function to insert a new_node in a list in sorted way.
Note that this function expects a pointer to head node
as this can modify the head of the input linked list */
void sortedInsert(struct Node** head_ref, struct Node* new_node)
{

// Case 1 of the above algo
if (current == NULL)
{
new_node->next = new_node;
}

// Case 2 of the above algo
else if (current->data >= new_node->data)
{
/* If value is smaller than head's value then
we need to change next of last node */
current = current->next;
current->next = new_node;
}

// Case 3 of the above algo
else
{
/* Locate the node before the point of insertion */
current->next->data < new_node->data)
current = current->next;

new_node->next = current->next;
current->next = new_node;
}
}

/* Function to print nodes in a given linked list */
void printList(struct Node *start)
{
struct Node *temp;

if(start != NULL)
{
temp = start;
printf("\n");
do {
printf("%d ", temp->data);
temp = temp->next;
} while(temp != start);
}
}

/* Driver program to test above functions */
int main()
{
int arr[] = {12, 56, 2, 11, 1, 90};
int list_size, i;

struct Node *start = NULL;
struct Node *temp;

/* Create linked list from the array arr[].
Created linked list will be 1->2->11->12->56->90 */
for (i = 0; i< 6; i++)
{
temp = (struct Node *)malloc(sizeof(struct Node));
temp->data = arr[i];
sortedInsert(&start, temp);
}

printList(start);

return 0;
}
```

## Java

```// Java program for sorted insert in circular linked list

class Node
{
int data;
Node next;

Node(int d)
{
data = d;
next = null;
}
}

{

// Constructor

/* function to insert a new_node in a list in sorted way.
Note that this function expects a pointer to head node
as this can modify the head of the input linked list */
void sortedInsert(Node new_node)
{

// Case 1 of the above algo
if (current == null)
{
new_node.next = new_node;

}

// Case 2 of the above algo
else if (current.data >= new_node.data)
{

/* If value is smaller than head's value then
we need to change next of last node */
current = current.next;

current.next = new_node;
}

// Case 3 of the above algo
else
{

/* Locate the node before the point of insertion */
current.next.data < new_node.data)
current = current.next;

new_node.next = current.next;
current.next = new_node;
}
}

// Utility method to print a linked list
void printList()
{
{
do
{
System.out.print(temp.data + " ");
temp = temp.next;
}
}

// Driver code to test above
public static void main(String[] args)
{

int arr[] = new int[] {12, 56, 2, 11, 1, 90};

Node temp = null;

/* Create linked list from the array arr[].
Created linked list will be 1->2->11->12->56->90*/
for (int i = 0; i < 6; i++)
{
temp = new Node(arr[i]);
list.sortedInsert(temp);
}

list.printList();
}
}

// This code has been contributed by Mayank Jaiswal
```

## Python

```# Node class
class Node:

# Constructor to initialize the node object
def __init__(self, data):
self.data = data
self.next = None

def __init__(self):

# Function to insert a new node at the beginning
def push(self, new_data):
new_node = Node(new_data)

def printList(self):
print temp.data,
temp = temp.next
print temp.data,
temp = temp.next

""" function to insert a new_node in a list in sorted way.
Note that this function expects a pointer to head node
as this can modify the head of the input linked list """
def sortedInsert(self, new_node):

# Case 1 of the above algo
if current is None:
new_node.next = new_node

# Case 2 of the above algo
elif (current.data >= new_node.data):

# If value is smaller than head's value then we
# need to change next of last node
current = current.next
current.next = new_node

# Case 3 of the above algo
else:

# Locate the node before the point of insertion
current.next.data < new_node.data):
current = current.next

new_node.next = current.next
current.next = new_node

# Driver program to test the above function
arr = [12, 56, 2, 11, 1, 90]

list_size = len(arr)

# Create linked list from the array arr[]
# Created linked list will be 1->2->11->12->56->90
for i in range(list_size):
temp = Node(arr[i])
start.sortedInsert(temp)

start.printList()

# This code is contributed by Nikhil Kumar Singh(nickzuck_007)

```

Output:

`1 2 11 12 56 90`

Time Complexity: O(n) where n is the number of nodes in the given linked list.

Case 2 of the above algorithm/code can be optimized. Please see this comment from Pavan. To implement the suggested change we need to modify the case 2 to following.

```
// Case 2 of the above algo
else if (current->data >= new_node->data)
{
// swap the data part of head node and new node
// assuming that we have a function swap(int *, int *)
swap(&(current->data), &(new_node->data));

}
```

Please write comments if you find the above code/algorithm incorrect, or find other ways to solve the same problem.

# GATE CS Corner    Company Wise Coding Practice

2.2 Average Difficulty : 2.2/5.0
Based on 126 vote(s)