708 Insert into a Cyclic Sorted List
1. Question
2. Implementation
/*
// Definition for a Node.
class Node {
public int val;
public Node next;
public Node() {}
public Node(int _val,Node _next) {
val = _val;
next = _next;
}
};
*/
class Solution {
public Node insert(Node head, int insertVal) {
if (head == null) {
Node node = new Node(insertVal);
node.next = node;
return node;
}
Node curNode = head;
while (curNode != null && curNode.next != null) {
if (curNode.val < curNode.next.val) {
if (curNode.val <= insertVal && insertVal <= curNode.next.val) {
break;
}
}
else if (curNode.val > curNode.next.val) {
if (insertVal > curNode.val || insertVal < curNode.next.val) {
break;
}
}
else {
if (curNode.next == head) {
break;
}
}
curNode = curNode.next;
}
insertNode(curNode, insertVal);
return head;
}
public void insertNode(Node curNode, int val) {
if (curNode == null) return;
Node node = new Node(val);
node.next = curNode.next;
curNode.next = node;
}
}3. Time & Space Complexity
Last updated