708. Insert into a Sorted Circular Linked List
Linked List, AMateList ·Problem Statement
link: LeetCode.cn LeetCode Given a Circular Linked List node, which is sorted in non-descending order, write a function to insert a value insertVal into the list such that it remains a sorted circular list. The given node can be a reference to any single node in the list and may not necessarily be the smallest value in the circular list.
If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the circular list should remain sorted.
If the list is empty (i.e., the given node is null), you should create a new single circular list and return the reference to that single node. Otherwise, you should return the originally given node.
Example:
Input: head = [3,4,1], insertVal = 2
Output: [3,4,1,2]
Input: head = [], insertVal = 1
Output: [1]
Input: head = [1], insertVal = 0
Output: [1, 0]
Constraints: The number of nodes in the list is in the range [0, 5 * 10^4]. -10^6 <= Node.val, insertVal <= 10^6
Solution Approach
Algorithm
Complexity
time complexity: O(n) space complexity: O(1)
Implement
class Node:
def __init__(self, val=None, next=None):
self.val = val
self.next = next
class Solution:
def insert(self, head: 'Optional[Node]', insertVal: int) -> 'Node':
newnode = Node(insertVal)
if not head:
newnode.next = newnode
return newnode
if head.next == head:
head.next = newnode
newnode.next = head
return head
pre = head
while pre.next and pre.next != head:
if pre.next.val >= pre.val:
pre = pre.next
else:
break
if pre.val <= insertVal:
newnode.next = pre.next
pre.next = newnode
else:
while pre.next and pre.next.val<insertVal:
pre = pre.next
newnode.next = pre.next
pre.next = newnode
return head