⚡Flashcard Drill➔
NeetCode #312LC-708MediumLinked ListNC Algo100
← Back to All Problems

#312 · #708 · Insert into a Sorted Circular Linked List(循环有序列表的插入)

📌 Problem Statement & Constraints

Given the head of a sorted circular linked list and an integer insertVal, insert the value so the list remains sorted, and return the head. The list may be empty, and insertVal may be smaller than all values or larger than all values. Constraints: the number of nodes is in [0, 5 * 10^4], -10^6 <= insertVal <= 10^6.

💡 Core Algorithmic Approaches

  1. Handle the empty list first: the new node points to itself.
  2. Walk the list looking for the correct insertion point. There are two cases: the value fits between prev and cur normally, or we are at the rotation point (where prev.val > cur.val, i.e. the maximum wraps to the minimum) and the value is outside the range.
  3. Also stop if we have come back to the head, which happens when every value is equal.
  4. Insert between prev and cur and return the original head.

💻 Benchmark Python3 Implementation

class Solution:
    def insert(self, head: "Optional[Node]", insertVal: int) -> "Node":
        node = Node(insertVal)
        if not head:                       # empty list
            node.next = node
            return node
        prev, cur = head, head.next
        while True:
            if prev.val <= insertVal <= cur.val:
                break                      # fits in the normal order
            if prev.val > cur.val and (insertVal >= prev.val or insertVal <= cur.val):
                break                      # outside the range at the rotation point
            prev, cur = cur, cur.next
            if prev is head:
                break                      # all values equal -> insert anywhere
        prev.next = node
        node.next = cur
        return head

⚡ Complexity Deep Dive

⏱️ Time Complexity
O(n): one pass around the circle in the worst case.
💾 Space Complexity
O(1): one new node.

⚠️ Interview Pitfalls & Follow-ups

  • Forgetting the rotation-point case: when the value is larger than the maximum or smaller than the minimum, it must be inserted at the wrap-around, not between two ordered neighbours.
  • Looping forever when all values are equal: the prev is head check breaks the loop.
  • Returning the new node as the head: the head should remain the original head (the problem accepts any valid rotation, but returning the original is conventional).
  • Not handling the empty list: head.next would raise an AttributeError.
⚡
Test muscle memory on this topic via 3-Layer Flashcards
Active Recall: Mentally formulate Prompt ➔ Math Derivation ➔ Benchmark Implementation in 3 minutes.
🎯 Drill This Card Now➔

🧩 Related Linked List Problems

中文速览与面试要点

循环有序列表的插入

给定循环 单调非递减 列表中的一个点,写一个函数向这个列表中插入一个新元素 insertVal,使这个列表仍然是循环升序的。给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。如果有多个满足条件的插入位置,可以选择任意一个位置插入新的值,插入后仍保证整个列表仍然是循环升序的。如果列表为空(给定的节点是 null),需要创建一个循环有序列表并返回这个节点。否则。请返回原先给定的节点。约束:0 ≤ 节点数 ≤ 5 × 10^4;-10^6 ≤ Node.val, insertVal ≤ 10^6。

核心要点

  • 遍历找插入点(标准解) :从 head 开始遍历一圈,找到满足以下任一条件的位置:
  • ① 常规情况 : prev.val &lt;= insertVal &lt;= cur.val ,直接插在中间。
  • ② 跨越最大→最小转折 : prev.val &gt; cur.val (说明 prev 是最大值、cur 是最小值),此时若 insertVal &gt;= prev.val (比最大值还大)或 insertVal &lt;= cur.val (比最小值还小),插在这里。
  • ③ 遍历一圈都没找到 :说明所有值都相同,插在 head 之后即可。
  • 空列表处理 :创建自环节点并返回。

常见陷阱

  • 只判断 prev.val &lt;= insertVal &lt;= cur.val :会漏掉「insertVal 比所有值都大或都小」的情况,此时应插在最大→最小的转折处。
  • 不处理「所有值相同」的情况 :此时不存在转折点,遍历一圈后仍未 break,会死循环。必须加 prev is head 的退出条件。
  • 空列表时忘记创建自环 : node.next = node 是必须的。
  • 返回 node 而非 head :题目要求返回 原先给定的节点 (除空列表外)。
  • 循环条件用 while prev != head :初始时 prev 就是 head,会导致循环体不执行。应使用 while True + 内部判断。

参考实现

class Solution:
    def insert(self, head: 'Node', insertVal: int) -> 'Node':
        node = Node(insertVal)
        if head is None:                    # 空列表 -> 自环
            node.next = node
            return node

        prev, cur = head, head.next
        while True:
            if prev.val <= insertVal <= cur.val:
                break                       # 常规插入点
            if prev.val > cur.val and (insertVal >= prev.val or insertVal <= cur.val):
                break                       # 跨越最大->最小的转折点
            prev, cur = cur, cur.next
            if prev is head:                # 已遍历一圈
                break

        prev.next = node
        node.next = cur
        return head