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):
#case1 node = None
#case 2.a node.val bigger than max => find max and find min
#case 2.b node.val between min and max (assuming there is min and max => at least 2 nodes =>
if not node:
node = ListNode(x)
node.next = node
return node
max = node # find max in linkedlist
head = node
while (head != max.next and max.next.val >= max.val):
max = max.next # update max
# to prevent deadloop, set up head and check with node.next
min = max.next
# case 2.a insertion
if x >= max.val or x <= min.val:
newNode = ListNode(x,min)
max.next = newNode
else:
cur = min
while cur.next.val < x :
cur = cur.next
newNode = ListNode(x,cur.next)
cur.next = newNode
return newNode