πInsert into a Sorted Circular Linked List
Problem:
Understanding of the problem
Solution
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node() {}
public Node(int _val) {
val = _val;
}
public Node(int _val, Node _next) {
val = _val;
next = _next;
}
};
*/
class Solution {
public Node insert(Node head, int insertVal) {
// Time complexity: O(n), n=> number of nodes
// Space complexity: Auxillary space
// Edge case
if(head==null) {
Node newNode = new Node(insertVal);
newNode.next = newNode;
return newNode;
}
Node current = head;
while(current.next != head) {
if(current.val <= current.next.val) { // When traversing forward, regulaar case
// Figure out in between
if(current.val <= insertVal && insertVal <= current.next.val) {
break;
}
} else { // When circular link is there
// Check if insertval should be between first and last
if(current.val <= insertVal || insertVal <= current.next.val) {
break;
}
}
current = current.next;
}
// Rearranging the links
Node newNode = new Node(insertVal,current.next);
current.next = newNode;
return head;
}
}Last updated


