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
Example
python
Given a list, and insert a value 4
:
3->5->1
Return 5->1->3->4
java
/**
* 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
ListNode n = new ListNode(x);
if (node == null) {
n.next = n;
return n;
}
ListNode curr = node.next;
ListNode prev = node;
while (curr != node) {
if (prev.val <= x && curr.val >= x) {
break;
}
if (prev.val > curr.val && (prev.val < x || curr.val > x)) {
break;
}
curr = curr.next;
prev = prev.next;
}
prev.next = n;
n.next = curr;
return node;
}
}
python
"""
Definition of ListNode
class ListNode(object):
def __init__(self, val, next=None):
self.val = val
self.next = next
"""
class Solution:
"""
@param: node: a list node in the list
@param: x: An integer
@return: the inserted new list node
"""
def insert(self, node, x):
# write your code here
n = ListNode(x)
if node is None:
n.next = n
return n
prev, curr = node, node.next
while curr != node:
if prev.val <= x and curr.val >= x:
break
if prev.val > curr.val and (prev.val < x or curr.val > x):
break
curr, prev = curr.next, prev.next
prev.next = n
n.next = curr
return node