![]() |
VOOZH | about |
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
👁 Image
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.
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
datais less thanhead, 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.
Illustration:
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)