708. Insert into a Cyclic Sorted List - Medium
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.
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.
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.
The following example may help you understand the problem better:
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.
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.
ref: https://www.cnblogs.com/grandyang/p/9981163.html
三种基本情况:
(1) 当链表为空时,生成一个新的list node,next指向自己,return
(2) 普通情况:要插入的元素比最小值大,比最大值小,直接插入即可
(3) 特殊情况:要插入的元素比最大值大,或者比最小值小,break出循环,单独处理
details:
两个指针 prev, cur 从head.next进入环形链表,走一圈:
(2) 如果prev < cur,说明当前处于升序中,此时如果要插入的值比prev大,比cur小,则可以插入,break出循环,直接插入并返回head即可;(2)
(3) 如果prev > cur,说明当前处于升序列的末端,此时如果要插入的值比prev大,或者比cur小,那么可以插入,break出循环,插入新元素并返回head即可.
time: O(n), space: O(1)
/* // 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) { head = new Node(insertVal, null); head.next = head; return head; } Node prev = head, cur = head.next; while(cur != head) { if(prev.val <= insertVal && cur.val >= insertVal) { break; } if(prev.val > cur.val && (insertVal >= prev.val || insertVal <= cur.val)) { break; } prev = cur; cur = cur.next; } prev.next = new Node(insertVal, cur); return head; } }