VOOZH about

URL: https://www.geeksforgeeks.org/dsa/sorted-insert-for-circular-linked-list/

⇱ Sorted insert for circular linked list - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Sorted insert for circular linked list

Last Updated : 17 May, 2025

Given a sorted circular linked list, your task is to insert a new node in this circular list so that it remains a sorted circular linked list.

Examples:

Input: head = 1 →2 →4, data = 2
Output: 1 →2 →2 →4
Explanation: We can add 2 after the second node.
👁 Image
Input: head = 1 →4 →7 →9, data = 5
Output: 1 →4 →5 →7 →9
Explanation: We can add 5 after the second node.

👁 Image

Approach:

To inset the newNode in the circular Linked List follow below :

  • Allocate memory for the newNode with the given data.
  • If the list is empty, update the head to point to the newNode.
  • If data is less than head, create a new node, link it after the last node, and return it as the new head.
  • Else, traverse to find the position where input data is smaller or equal to head's data and insert newNode by adjusting the necessary pointers.
  • Otherwise, insert the newNode in its appropriate position which is data <= head  →data:

Illustration:


Output
3 7 8 9 11 

Time Complexity: O(n), where n is the number of nodes in the given circular linked list.
Auxiliary Space: O(1)

Comment