Given a node from a cyclic linked list which has been sorted, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list. Return the inserted new node.
Notice
3->5->1 is a cyclic list, so 3 is next node of 1.
3->5->1 is same with 5->1->3
Have you met this question in a real interview? Yes
Example
Given a list, and insert a value 4:
3->5->1
Return 5->1->3->4
1 /*
2 * @param node: a list node in the list
3 * @param x: An integer
4 * @return: the inserted new list node
5 */
6 public ListNode insert(ListNode node, int x) {
7 // write your code here
8 // 在是空的情况,一个node也要首尾相连
9 if (node == null) {
10 ListNode newNode = new ListNode(x);
11 newNode.next = newNode;
12 return newNode;
13 }
14 ListNode curr = node ;
15 /*
16 * 3->5->1 node = 1, x =4
17 Return 5->1->3->4
18 * */
19 //没有循环一圈, node 是初始位置的节点
20 while (curr!=null && curr.next != node ) {
21 //把4 加入到 3 和 5 中间
22 if (curr.val <=x && curr.next.val>x) {
23 break;
24 }
25 curr = curr.next;
26 }
27 //当前 curr 是 3
28 ListNode temp = curr.next;
29 ListNode newNode = new ListNode(x);
30 curr.next = newNode;
31 newNode.next = temp;
32 return curr ;
33 }