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.
解题:
需要考虑listnode 为null, 单个node, 2-2-2-2-2-2等特殊情况。
做一次do while 去check是否有222222类似循环
/**
* Definition for ListNode
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
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) {
// Write your code here
if(node == null){
ListNode newNode = new ListNode(x);
newNode.next = newNode;
return newNode;
}
if(node.next == null || node.next == node){
ListNode newNode = new ListNode(x);
newNode.next = node;
node.next = newNode;
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;
}
}