[LeetCode] replace into a Cyclic Sorted List

Question:

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.


http://leetcode.com/2011/08/insert-into-a-cyclic-sorted-list.html


// Given a node from circled sorted list, find the min node.
private ListNode findMin(ListNode node)
{
    while (node.next.val >= node.val)
        node = node.next;
    return node.next;
}

// Insert some node into a circled sorted list
// start from a smaller node. (guarantee smallnode.val <= newnode.val)
// Thus before loop the whole circle, we must can insert the new node.
private void insertFromASmallNode(ListNode smallnode, ListNode newnode)
{
    // Guarantee smallnode.val <= newnode.val
    while (smallnode.next.val < newnode.val)
    {
        smallnode= smallnode.next;
    }
    // Find insert place, insert newnode after smallnode;
    newnode.next = smallnode.next;
    smallnode.next = newnode;
}

// O(n)
public void insert(ListNode node, ListNode newnode)
{
    // Assumptions...
    if (node.val > newnode.val)
        node = findMin(node);
    insertFromASmallNode(node, newnode);  
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章