[LintCode] Insert into a Cyclic Sorted List

发布时间:2019-06-18 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LintCode] Insert into a Cyclic Sorted List脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

PRoblem

Given a node From a cyclic linked list which has been sorted, wrITe a function to insert a value into the list such that it remains a cyclic sorted list. The given node can be any single node in the list. Return the inserted new node.

Notice

3->5->1 is a cyclic list, so 3 is next node of 1.
3->5->1 is same with 5->1->3

Example

Given a list, and insert a value 4:
3->5->1
Return 5->1->3->4

Tags

Amazon Linked List

Solution

public class Solution {
    public ListNode insert(ListNode node, int x) {
        ListNode head = node;
        if (node == null) {
            node = new ListNode(x);
            node.next = node;
            return node;
        }
        if (node.next == head) {
            insertNode(node, x);
            return head;
        }
        while (node != null && node.next != null) {
            if (node.val < node.next.val) {
                if (node.val <= x && x <= node.next.val) {
                    insertNode(node, x);
                    break;
                }
            } else if (node.val > node.next.val) {
                if (x >= node.val || x <= node.next.val) {
                    insertNode(node, x);
                    break;
                }
            } else {
                if (node.next == head) {
                    insertNode(node, x);
                    break;
                }
            }
            node = node.next;
        }
        return head;
    }
    public void insertNode(ListNode head, int x) {
        ListNode node = new ListNode(x);
        node.next = head.next;
        head.next = node;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LintCode] Insert into a Cyclic Sorted List全部内容,希望文章能够帮你解决[LintCode] Insert into a Cyclic Sorted List所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。