Skip to main content

🟡 剑指 Offer II 029. 排序的循环链表

LeetCode 提示

题目难度 中等

原题链接 🔗 leetcode

题解1#

/*// Definition for a Node.class Node {    public int val;    public Node next;
    public Node() {}
    public Node(int _val) {        val = _val;    }
    public Node(int _val, Node _next) {        val = _val;        next = _next;    }};*/
class Solution {    public Node insert(Node head, int insertVal) {        Node newNode = new Node(insertVal);        if (head == null) {          newNode.next = newNode;          return newNode;        }
        Node cur = head.next;        Node pre = head;
        if (cur == pre) {          cur.next = newNode;          newNode.next = cur;          return head;        }
        for (;;) {          if (            (cur.val >= insertVal && insertVal >= pre.val)            ||            ((insertVal >= pre.val || insertVal <= cur.val) && cur.val < pre.val)            ||            (cur == head)          ) {            pre.next = newNode;            newNode.next = cur;            return head;          }          cur = cur.next;          pre = pre.next;        }    }}