class Solution {

    private static ListNode function(ListNode head, int num) {
        if (head == null) {
            return null;
        }
        // find the tail
        ListNode tail = head;
        while (tail.next != head) {
            tail = tail.next;
        }
        ListNode pre = tail;
        ListNode cur = head;
        // find the first element >= num
        do {
            if (cur.val >= num) {
                break;
            }
            pre = pre.next;
            cur = cur.next;
        } while (cur != tail);
        ListNode newNode = new ListNode(num);
        ListNode next = pre.next;
        // head changed
        if (next == head) {
            head = newNode;
        }
        pre.next = newNode;
        newNode.next = next;
        return head;
    }

    private static void print(ListNode head, Integer limit) {
        if (limit == null) {
            limit = Integer.MAX_VALUE;
        }
        while (head != null && limit -- > 0) {
            System.out.println(head.val);
            head = head.next;
        }
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
        ListNode n2 = new ListNode(3);
        ListNode n3 = new ListNode(4);
        ListNode n4 = new ListNode(5);
        ListNode n5 = new ListNode(7);
        ListNode n6 = new ListNode(7);
        ListNode n7 = new ListNode(8);
        ListNode n8 = new ListNode(9);
        n1.next = n2;
        n2.next = n3;
        n3.next = n4;
        n4.next = n5;
        n5.next = n6;
        n6.next = n7;
        n7.next = n8;
        n8.next = n1;

        ListNode head = function(n1, 0);


        print(head, 10);

    }
}

class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}