708. Insert into a Cyclic Sorted List
class Node {
public:
int val;
Node* next;
Node() {}
Node(int _val, Node* _next) {
val = _val;
next = _next;
}
};Node* insert(Node* head, int insertVal) { // time: O(n); space: O(1)
if (!head) {
head = new Node(insertVal, nullptr);
head->next = head;
return head;
}
Node *pre = head, *cur = pre->next;
while (cur != head) {
// Two cases to insert
// 1. find insertval is in [pre->val, cur->val]
// 2. find a inverting point and insertVal is larger than max or insertVal is smaller than min of the cyclic list
if (pre->val <= insertVal && cur->val >= insertVal) break;
if (pre->val > cur->val && (pre->val <= insertVal || cur->val >= insertVal)) break;
pre = cur;
cur = cur->next;
}
pre->next = new Node(insertVal, cur);
return head;
}Last updated

