给定循环单调非递减列表中的一个点,写一个函数向这个列表中插入一个新元素 insertVal ,使这个列表仍然是循环升序的。
给定的可以是这个列表中任意一个顶点的指针,并不一定是这个列表中最小元素的指针。
如果有多个满足条件的插入位置,可以选择任意一个位置插入新的值,插入后整个列表仍然保持有序。
如果列表为空(给定的节点是 null),需要创建一个循环有序列表并返回这个节点。否则。请返回原先给定的节点。
示例 1:
输入:head = [3,4,1], insertVal = 2
输出:[3,4,1,2]
解释:在上图中,有一个包含三个元素的循环有序列表,你获得值为 3 的节点的指针,我们需要向表中插入元素 2 。新插入的节点应该在 1 和 3 之间,插入之后,整个列表如上图所示,最后返回节点 3 。
示例 2:
输入:head = [], insertVal = 1
输出:[1]
解释:列表为空(给定的节点是 null),创建一个循环有序列表并返回这个节点。
示例 3:
输入:head = [1], insertVal = 0
输出:[1,0]
提示:
0 <= Number of Nodes <= 5 * 10^4
-10^6 <= Node.val <= 10^6
-10^6 <= insertVal <= 10^6
注意:本题与主站 708 题相同: https://leetcode-cn.com/problems/insert-into-a-sorted-circular-linked-list/
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/4ueAj6
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解析:首先,如果是普通插入很简单,只需要找到 前一个节点小,后一个节点大的位置进行插入,本题难点在于边界情况,如果给的值都大于链表中的值,或者都小于链表中的值,就找不到 前一个小,后一个大的位置了,所以这个时候应该插入当前链表最大值的后面,这样构成一个循环
还有更边界的情况,如果给的 head 是空,那么插入以后应该是自己指向自己,剩下的情况,都是上文说的情况
循环结束的条件是,找到 满足的节点或者 next 等于 head 也就是转了一圈以后,需要注意的是,如果插入在最大值之后,不能设置为 next = haed 因为 题目中虽然说了是递增,但是没有说头结点是最小的
/*
// 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 node = new Node(insertVal);
if (head == null) {
head = node;
head.next = head;
} else {
insertCore(head, node);
}
return head;
}
public void insertCore(Node head, Node node) {
Node cur = head;
Node next = head.next;
Node biggest = head;
while (!(cur.val <= node.val && next.val >= node.val) && next != head) {
cur = cur.next;
next = next.next;
if (cur.val >= biggest.val) {
biggest = cur;
}
}
if (cur.val <= node.val && next.val >= node.val) {
cur.next = node;
node.next = next;
} else {
node.next = biggest.next;
biggest.next = node;
}
}
}