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;
    }
}

linspiration
161 声望53 粉丝