Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Linked List
  • Practice Linked List
  • MCQs on Linked List
  • Linked List Tutorial
  • Types of Linked List
  • Singly Linked List
  • Doubly Linked List
  • Circular Linked List
  • Circular Doubly Linked List
  • Linked List vs Array
  • Time & Space Complexity
  • Advantages & Disadvantages
Open In App
Next Article:
Insertion in Circular Singly Linked List
Next article icon

Sorted insert for circular linked list

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a sorted Circular Linked List. The task is to insert the given data in a sorted way.

Examples:

Input:

Sorted-insert-for-circular-linked-list

Output:

Sorted-insert-for-circular-linked-list-2

Explanation: 8 is inserted after 7 and before 9 to preserve the sorted order.


Input:

Sorted-insert-for-circular-linked-list-3

Output:

Sorted-insert-for-circular-linked-list-4

Explanation: 1 will be inserted at the beginning of circular linked list.

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.
  • Otherwise, insert the newNode in its appropriate position which is data <= head->data:
    • If inserting before the head , traverse till last node, update it's next to newNode and then update the head to newNode.
    • 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.

Below is the implementation of the above approach: 

C++
// C++ program for sorted insert // in circular linked list  #include <iostream> using namespace std;  class Node {  public:     int data;      Node *next;      Node(int x) {          data = x;          next = nullptr;      }  };   // Function to insert a new node in the  // list in a sorted way Node* sortedInsert(Node* head, int data) {      	// Create the new node with the given data     Node* newNode = new Node(data);           // If linked list is empty     if (head == nullptr) {         newNode->next = newNode;          head = newNode;         return head;     }          Node* curr = head;     Node* nextToCurr = head->next;          // Insert at the beginning if data is less    	// than or equal to head's data     if (data <= head->data) {         Node* lastNode = head;         while (lastNode->next != head) {           	           	// Find the last node             lastNode = lastNode->next;          }              	// Set new node's next to head         newNode->next = head;                 	// Update last node's next to new node       	lastNode->next = newNode;                 	// Update head to new node       	head = newNode;          return head;     }          // Insert in the middle of the list     while (curr->next != head) {         if (curr->data < data && nextToCurr->data >= data) {           	           	// Set new node's next to current's next             newNode->next = curr->next;              curr->next = newNode;             return head;         } else {                      	// Move to the next node             curr = curr->next;              nextToCurr = nextToCurr->next;          }     }          // Insert at the end of the list     newNode->next = head;      curr->next = newNode;      return head; }  void printList(Node *head) {      Node *curr = head;          if (head != nullptr) {          do {              cout << curr->data << " ";              curr = curr->next;          } while (curr != head);          cout << endl;      }  }  int main()  {        // Create circular linked list: 3->7->9->11->3     Node *head = new Node(3);     head->next = new Node(7);     head->next->next = new Node(9);     head->next->next->next = new Node(11);     head->next->next->next->next = head;    	     head = sortedInsert(head, 8);      printList(head);      return 0;  }  
C
// C program for sorted insert in  // circular linked list  #include <stdlib.h>  struct Node {     int data;     struct Node *next; };  struct Node* createNode(int data) {     struct Node* newNode =        (struct Node*)malloc(sizeof(struct Node));     newNode->data = data;     newNode->next = NULL;     return newNode; }  // Function to insert a new node  // in the list in a sorted way struct Node* sortedInsert(struct Node* head, int data) {        // Create the new node with the given data     struct Node* newNode = createNode(data);          // If linked list is empty     if (head == NULL) {         newNode->next = newNode;         head = newNode;         return head;     }          struct Node* curr = head;     struct Node* nextToCurr = head->next;          // Insert at the beginning if data is    	// less than or equal to head's data     if (data <= head->data) {         struct Node* lastNode = head;         while (lastNode->next != head) {             // Find the last node             lastNode = lastNode->next;         }                  // Set new node's next to head         newNode->next = head;                	// Update last node's next to new node         lastNode->next = newNode;                	// Update head to new node         head = newNode;         return head;     }          // Insert in the middle of the list     while (curr->next != head) {         if (curr->data < data && nextToCurr->data >= data) {                        // Set new node's next to current's next             newNode->next = curr->next;             curr->next = newNode;             return head;         } else {                        // Move to the next node             curr = curr->next;             nextToCurr = nextToCurr->next;         }     }          // Insert at the end of the list     newNode->next = head;     curr->next = newNode;     return head; }  // Function to print nodes in a // given circular linked list void printList(struct Node *head) {     struct Node *curr = head;          if (head != NULL) {         do {             printf("%d ", curr->data);             curr = curr->next;         } while (curr != head);         printf("\n");     } }  int main() {        // Create circular linked list: 3->7->9->11->3     struct Node *head = createNode(3);     head->next = createNode(7);     head->next->next = createNode(9);     head->next->next->next = createNode(11);     head->next->next->next->next = head;        head = sortedInsert(head, 8);     printList(head);          return 0; } 
Java
// Java program for sorted insert // in circular linked list  class Node {     int data;     Node next;      Node(int x) {         data = x;         next = null;     } }  public class GfG {          // Function to insert a new node in the    	// list in a sorted way     static Node sortedInsert(Node head, int data) {                  // Create the new node with the given data         Node newNode = new Node(data);                  // If linked list is empty         if (head == null) {             newNode.next = newNode;             return newNode;         }          Node curr = head;         Node nextToCurr = head.next;          // Insert at the beginning if data is        	// less than or equal to head's data         if (data <= head.data) {             Node lastNode = head;             while (lastNode.next != head) {                                  // Find the last node                 lastNode = lastNode.next;             }              // Set new node's next to head             newNode.next = head;              // Update last node's next to new node             lastNode.next = newNode;              // Update head to new node             return newNode;         }          // Insert in the middle of the list         while (curr.next != head) {             if (curr.data < data && nextToCurr.data >= data) {                                  // Set new node's next to current's next                 newNode.next = curr.next;                 curr.next = newNode;                 return head;             } else {                                  // Move to the next node                 curr = curr.next;                 nextToCurr = nextToCurr.next;             }         }          // Insert at the end of the list         newNode.next = head;         curr.next = newNode;         return head;     }      // Function to print nodes in a    	// given circular linked list     static void printList(Node head) {         Node curr = head;          if (head != null) {             do {                 System.out.print(curr.data + " ");                 curr = curr.next;             } while (curr != head);             System.out.println();         }     }      public static void main(String[] args) {                // Create circular linked list: 3->7->9->11->3         Node head = new Node(3);         head.next = new Node(7);         head.next.next = new Node(9);         head.next.next.next = new Node(11);         head.next.next.next.next = head;          head = sortedInsert(head, 8);         printList(head);     } } 
Python
# python program for sorted insert in  # circular linked list class Node:     def __init__(self, data):         self.data = data         self.next = None  # Function to insert a new node in # the list in a sorted way def sortedInsert(head, data):     new_node = Node(data)      # If linked list is empty     if head is None:         new_node.next = new_node         return new_node      curr = head     next_to_curr = head.next      # Insert at the beginning if data is less     # than or equal to head's data     if data <= head.data:         last_node = head         while last_node.next != head:             last_node = last_node.next         new_node.next = head         last_node.next = new_node         return new_node      # Insert in the middle of the list     while curr.next != head:         if curr.data < data and next_to_curr.data >= data:             new_node.next = curr.next             curr.next = new_node             return head         else:             curr = curr.next             next_to_curr = next_to_curr.next      # Insert at the end of the list     new_node.next = head     curr.next = new_node     return head  def printList(head):     curr = head     if head is not None:         while True:             print(curr.data, end=" ")             curr = curr.next             if curr == head:                 break         print()   if __name__ == "__main__":        # Create circular linked list: 3->7->9->11->3     head = Node(3)     head.next = Node(7)     head.next.next = Node(9)     head.next.next.next = Node(11)     head.next.next.next.next = head      head = sortedInsert(head, 8)     printList(head) 
C#
// C# program for sorted insert // in circular linked list  using System;  class Node {     public int data;     public Node next;      public Node(int x) {         data = x;         next = null;     } }  class GfG {      // Function to insert a new node in the list in a sorted     // way     static Node SortedInsert(Node head, int data) {          // Create the new node with the given data         Node newNode = new Node(data);          // If linked list is empty         if (head == null) {             newNode.next = newNode;             return newNode;         }          Node curr = head;         Node nextToCurr = head.next;          // Insert at the beginning if data is         // less than or equal to head's data         if (data <= head.data) {             Node lastNode = head;             while (lastNode.next != head) {                  // Find the last node                 lastNode = lastNode.next;             }              // Set new node's next to head             newNode.next = head;              // Update last node's next to new node             lastNode.next = newNode;              // Update head to new node             return newNode;         }          // Insert in the middle of the list         while (curr.next != head) {             if (curr.data < data                 && nextToCurr.data >= data) {                  // Set new node's next to current's next                 newNode.next = curr.next;                 curr.next = newNode;                 return head;             }             else {                  // Move to the next node                 curr = curr.next;                 nextToCurr = nextToCurr.next;             }         }          // Insert at the end of the list         newNode.next = head;         curr.next = newNode;         return head;     }      // Function to print nodes in a given circular linked     // list     static void PrintList(Node head) {         Node curr = head;          if (head != null) {             do {                 Console.Write(curr.data + " ");                 curr = curr.next;             } while (curr != head);             Console.WriteLine();         }     }      static void Main(string[] args) {                // Create circular linked list: 3->7->9->11->3         Node head = new Node(3);         head.next = new Node(7);         head.next.next = new Node(9);         head.next.next.next = new Node(11);         head.next.next.next.next = head;                head = SortedInsert(head, 8);         PrintList(head);     } } 
JavaScript
// Javascript program for sorted insert in circular linked // list  class Node {     constructor(data) {         this.data = data;         this.next = null;     } }  // Function to insert a new node in  // the list in a sorted way function sortedInsert(head, data) {     let newNode = new Node(data);      // If linked list is empty     if (head === null) {         newNode.next = newNode;         return newNode;     }      let curr = head;     let nextToCurr = head.next;      // Insert at the beginning if data is     // less than or equal to head's data     if (data <= head.data) {         let lastNode = head;         while (lastNode.next !== head) {             lastNode = lastNode.next;         }         newNode.next = head;         lastNode.next = newNode;         return newNode;     }      // Insert in the middle of the list     while (curr.next !== head) {         if (curr.data < data && nextToCurr.data >= data) {             newNode.next = curr.next;             curr.next = newNode;             return head;         }         else {             curr = curr.next;             nextToCurr = nextToCurr.next;         }     }      // Insert at the end of the list     newNode.next = head;     curr.next = newNode;     return head; }  function printList(head) {     let curr = head;     if (head !== null) {         do {             console.log(curr.data + " ");             curr = curr.next;         } while (curr !== head);         console.log();     } }  // Create circular linked list: 3->7->9->11->3 let head = new Node(3); head.next = new Node(7); head.next.next = new Node(9); head.next.next.next = new Node(11); head.next.next.next.next = head;  head = sortedInsert(head, 8); printList(head); 

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)


Next Article
Insertion in Circular Singly Linked List
author
kartik
Improve
Article Tags :
  • Linked List
  • DSA
  • Microsoft
  • Amazon
  • Zoho
  • circular linked list
Practice Tags :
  • Amazon
  • Microsoft
  • Zoho
  • circular linked list
  • Linked List

Similar Reads

  • Insertion Sort for Doubly Linked List
    Given a doubly linked list, the task is to sort the doubly linked list in non-decreasing order using the insertion sort. Examples: Input: head: 5<->3<->4<->1<->2Output: 1<->2<->3<->4<->5Explanation: Doubly Linked List after sorting using insertion sort
    10 min read
  • Insertion in Circular Singly Linked List
    In this article, we will learn how to insert a node into a circular linked list. Insertion is a fundamental operation in linked lists that involves adding a new node to the list. In a circular linked list, the last node connects back to the first node, creating a loop. There are four main ways to ad
    12 min read
  • Count nodes in Circular linked list
    Given a circular linked list. The task is to find the length of the linked list, where length is defined as the number of nodes in the linked list. Using linear traversal - O(n) time and O(1) spaceThe idea is to start from the head node and traversing the list until it loops back to the head. Since
    5 min read
  • Insertion at the end in circular linked list
    A circular linked list is a data structure where each node points to the next, and the last node connects back to the first, creating a loop. Insertion at the end in circular linked list is an important operation. Understanding how to perform this insertion is essential for effectively manage and us
    7 min read
  • Sort a Linked List in wave form
    Given an unsorted Linked List of integers. The task is to sort the Linked List into a wave like Line. A Linked List is said to be sorted in Wave Form if the list after sorting is in the form: list[0] >= list[1] <= list[2] >= ….. Where list[i] denotes the data at i-th node of the Linked List
    11 min read
  • Insertion in Doubly Circular Linked List
    Circular Doubly Linked List has properties of both doubly linked list and circular linked list in which two consecutive elements are linked or connected by the previous and next pointer and the last node points to the first node by the next pointer and also the first node points to the last node by
    15+ min read
  • Circular Linked List in Python
    A Circular Linked List is a variation of the standard linked list. In a standard linked list, the last element points to null, indicating the end of the list. However, in a circular linked list, the last element points back to the first element, forming a loop. In this article, we will discuss the c
    13 min read
  • Introduction to Circular Linked List
    A circular linked list is a data structure where the last node connects back to the first, forming a loop. This structure allows for continuous traversal without any interruptions. Circular linked lists are especially helpful for tasks like scheduling and managing playlists, allowing for smooth navi
    15+ min read
  • Searching in Circular Linked list
    Given a Circular Linked List CList, and an element K, the task is to check if this element K is present in the Circular Linked list or not. Example: Input: CList = 6->5->4->3->2, K = 3 Output: Found Input: CList = 6->5->4->3->2, K = 1 Output: Not Found Approach: The approach
    7 min read
  • Introduction to Circular Doubly Linked List
    A circular doubly linked list is defined as a circular linked list in which each node has two links connecting it to the previous node and the next node. Characteristics of Circular Doubly Linked List :A circular doubly linked list has the following properties: Circular: A circular doubly linked lis
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences