708. Insert into a Cyclic Sorted List
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, next):
self.val = val
self.next = next
"""
class Solution(object):
def insert(self, head, insertVal):
"""
:type head: Node
:type insertVal: int
:rtype: Node
1. find the first prev where prev.val <= Val < prev.next.val
2.
1. find the first prev where prev.val > prev.next.val
Add after prev
"""
if head is None:
rst = Node(insertVal, None)
rst.next = rst
return rst
cur = head.next
isFirst = True # nice, one point for xixi
while(cur != head or isFirst):
if insertVal >= cur.val and insertVal <= cur.next.val:
nextNode = cur.next
cur.next = Node(insertVal, nextNode)
return head
if cur.val > cur.next.val and (insertVal >= cur.val or insertVal <= cur.next.val): #
nextNode = cur.next
cur.next = Node(insertVal, nextNode)
return head
cur = cur.next
isFirst = False
nextNode = cur.next
cur.next = Node(insertVal, nextNode)
return headLast updated