Given a Circular Linked List node, which is sorted in ascending 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 1:
Input: head = [3,4,1], insertVal = 2 Output: [3,4,1,2] Explanation: In the figure above, there is a sorted circular list of three elements. You are given a reference to the node with value 3, and we need to insert 2 into the list. The new node should be inserted between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.
Example 2:
Input: head = [], insertVal = 1
Output: [1]
Explanation: The list is empty (given head is null
). We create a new single circular list and return the reference to that single node.
Example 3:
Input: head = [1], insertVal = 0 Output: [1,0]
Constraints:
- The number of nodes in the list is in the range
[0, 5 * 104]
. -106 <= Node.val, insertVal <= 106
题目大意是给定一个循环链表,节点是按升序排好序的,现在要求在适当的位置插入一个数值(插入一个新节点) 且要保持链表还是升序的。还有给定的头指针并不一定是指向最小值的那个节点。如果有多个合适的位置可以插入就随便选一个位置插入。如果给定的链表为空则创建一个新节点使其自身形成一个只有单个节点的循环链表并返回该节点指针,否则要返回原来的头指针。
有以下三种情况:
1)如果链表为空,则创建一个新节点,把next指向自己,然后直接返回。
2)如果链表只有一个节点则创建一个新节点,跟给定的头结点互相指向对方,然后返回头结点。
3)如果链表多于一个节点,由于它是一个升序的循环链表,特点是除了最大值节点过渡到最小值节点的地方不是升序的,其他节点之间都是升序的。因此我们可以遍历整个链表,在最大值和最小值之间做特殊处理即可。定义两个指针pre = head, cur = head.next,如果pre.val小于等于cur.val说明是升序的只要判断插入值是否落在pre和cur之间,如果是插入即可;如果pre.val大于cur.val说明遇到了最大值过渡到最小值,这时要是给定值大于等于最大值pre.val或者小于等于最小值cur.val,则说明要在此处插入。循环
注:如果整个链表所有节点值都相等则没有最大值过渡到最小值的情况,但不影响情况3)的处理。
"""
# Definition for a Node.
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':
node = Node(insertVal)
if not head:
node.next = node
return node
if head.next == head:
head.next = node
node.next = head
return head
pre, cur = head, head.next
while cur != head:
if (pre.val > cur.val and (insertVal >= pre.val or insertVal <= cur.val)) or (insertVal >= pre.val and insertVal <= cur.val):
pre.next = node
node.next = cur
return head
pre, cur = cur, cur.next
pre.next = node
node.next = cur
return head