Given a node from a Circular Linked List which is sorted in ascending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the circular list.
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.
If the list is empty (i.e., given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the original given node.
Example 1:

Input: head = [3,4,1], insertVal = 2 Output: [3,4,1,2] Explanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.

Example 2:
Input: head = [], insertVal = 1
Output: [1]
Explanation: The list is empty (given head is null). We create a new single circular list and return the reference to that single node.
Example 3:
Input: head = [1], insertVal = 0 Output: [1,0]
Constraints:
0 <= Number of Nodes <= 5 * 10^4-10^6 <= Node.val <= 10^6-10^6 <= insertVal <= 10^6
這道題讓我們在循環有序的鏈表中插入結點,要求插入結點后,鏈表仍保持有序且循環。題目中強調了corner case的情況,就是當鏈表為空時,我們插入結點即要生成一個新的循環有序鏈表,那么我們可以先處理這個特殊情況,比較簡單,就是新建一個結點,然后將next指針指向自己即可。好,下面來看給定的鏈表不為空的情況,最常見的情況就是要插入的結點值在兩個有序結點值[a, b]之間,那么只要滿足 a <= insertVal <= b 即可。由於是循環有序的鏈表,結點值不會一直上升,到某一個結點的時候,是最大值,但是下一個結點就是最小值了,就是題目中的例子,結點4到結點1的時候,就是下降了。那么在這個拐點的時候,插入值insertVal就會有兩種特殊的情況,其大於等於最大值,或者小於等於最小值,比如插入值是5,或者0的時候,這兩種情況都插入在結點4之后,可以放一起處理。而若其小於最大值,或者大於最小值,就是上面那種一般的情況,不會在這里處理,所以我們只要檢測如果屬於上面的兩種情況之一,就break掉循環,進行插入結點處理即可,參見代碼如下:
class Solution { public: Node* insert(Node* head, int insertVal) { if (!head) { head = new Node(insertVal, NULL); head->next = head; return head; } Node *pre = head, *cur = pre->next; while (cur != head) { 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; } };
類似題目:
參考資料:
https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/
