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.
public class Solution {
/** * @param node a list node in the list * @param x an integer * @return the inserted new list node */
public ListNode insert(ListNode node, int x) {
if (node == null) {
node = new ListNode(x);
node.next = node;
return node;
}
ListNode point = node;
ListNode prev = null;
//循环一个周期
do {
prev = point;
point = point.next;
if (prev.val <= x && point.val >= x) {
break;
}
if ((prev.val > point.val) && (x > prev.val || x < point.val)) {
break;
}
} while (point != node);
ListNode newNode = new ListNode(x);
newNode.next = point;
prev.next = newNode;
return newNode;
}
}