Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted 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 cyclic list.html
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the cyclic list should remain sorted.java
If the list is empty (i.e., given node is null
), you should create a new single cyclic list and return the reference to that single node. Otherwise, you should return the original given node.node
The following example may help you understand the problem better:post
In the figure above, there is a cyclic sorted list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list.ui
The new node should insert between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.this
這道題讓咱們在循環有序的鏈表中插入結點,要求插入結點後,鏈表仍保持有序且循環。題目中強調了corner case的狀況,就是當鏈表爲空時,咱們插入結點即要生成一個新的循環有序鏈表,那麼咱們能夠先處理這個特殊狀況,比較簡單,就是新建一個結點,而後將next指針指向本身便可。好,下面來看給定的鏈表不爲空的狀況,最多見的狀況就是要插入的結點值在兩個有序結點值[a, b]之間,那麼只要知足 a <= insertVal <= b 便可。因爲是循環有序的鏈表,結點值不會一直上升,到某一個結點的時候,是最大值,可是下一個結點就是最小值了,就是題目中的例子,結點4到結點1的時候,就是降低了。那麼在這個拐點的時候,插入值insertVal就會有兩種特殊的狀況,其大於等於最大值,或者小於等於最小值,好比插入值是5,或者0的時候,這兩種狀況都插入在結點4以後,能夠放一塊兒處理。而若其小於最大值,或者大於最小值,就是上面那種通常的狀況,不會在這裏處理,因此咱們只要檢測若是屬於上面的兩種狀況之一,就break掉循環,進行插入結點處理便可,參見代碼以下:url
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; } };
相似題目:spa
參考資料:code
https://leetcode.com/problems/insert-into-a-cyclic-sorted-list/