Sunday, January 15, 2017

Insert into Cycle Linked List

Insert a new list node into a sorted cycle linked list.

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

import java.util.*;

class ListNode {
    int val;
    ListNode next;
    public ListNode(int val) {
        this.val = val;
        next = null;
    }
}
public class Solution {
    public static ListNode insertCycleLinkedList(ListNode head, 
                                                 int val) {
        ListNode curr = new ListNode(val);
        if (head == null) {
            curr.next = curr;
            return curr;
        }
        ListNode node = head;
        do {
            if (val >= node.val && val <= node.next.val) {
                break;
            } 
            if (node.val >= node.next.val && 
                (val >= node.val || val <= node.next.val)) {
                break;
            }
            node = node.next;
        } while (node != head);
        
        curr.next = node.next;
        node.next = curr;
        return curr;
    }

    public static void main(String[] args) {
        ListNode n1 = new ListNode (1);
        ListNode n2 = new ListNode (1);
        ListNode n3 = new ListNode (1);
        n1.next = n2;
        n2.next = n3;
        n3.next = n1;
        ListNode ans = insertCycleLinkedList(n1, 2);
        ListNode tmp = ans;
        do {
            System.out.print(tmp.val + " ");
            tmp = tmp.next;
        } while (tmp != ans);
    }
}

No comments:

Post a Comment