708. Insert into a Cyclic Sorted List - Medium

Given a node from a cyclic linked list which is sorted in ascending order, write a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be a reference to any single node in the list, and may not be necessarily the smallest value in the cyclic list.

If there are multiple suitable places for insertion, you may choose any place to insert the new value. After the insertion, the cyclic list should remain sorted.

If the list is empty (i.e., given node is null), you should create a new single cyclic list and return the reference to that single node. Otherwise, you should return the original given node.

The following example may help you understand the problem better:



In the figure above, there is a cyclic sorted 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 insert between node 1 and node 3. After the insertion, the list should look like this, and we should still return node 3.

ref: https://www.cnblogs.com/grandyang/p/9981163.html

当链表为空时,生成一个新的list node,next指向自己,return

扫描二维码关注公众号,回复: 4673414 查看本文章

普通情况:要插入的元素比最小值大,比最大值小,直接插入即可;特殊情况:要插入的元素比最大值大,或者比最小值小,break出循环,单独处理

time: O(n), space: O(1)

/*
// Definition for a Node.
class Node {
    public int val;
    public Node next;

    public Node() {}

    public Node(int _val,Node _next) {
        val = _val;
        next = _next;
    }
};
*/
class Solution {
    public Node insert(Node head, int insertVal) {
        if(head == null) {
            head = new Node(insertVal, null);
            head.next = head;
            return head;
        }
        Node prev = head, cur = head.next;
        while(cur != head) {
            if(prev.val <= insertVal && cur.val >= insertVal) {
                break;
            }
            if(prev.val > cur.val && (insertVal >= prev.val || insertVal <= cur.val)) {
                break;
            }
            prev = cur;
            cur = cur.next;
        }
        prev.next = new Node(insertVal, cur);
        
        return head;
    }
}

猜你喜欢

转载自www.cnblogs.com/fatttcat/p/10186653.html
今日推荐