[LintCode] Insert into a Cyclic Sorted List

 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.

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

 1 /**
 2  * Definition for ListNode
 3  * public class ListNode {
 4  *     int val;
 5  *     ListNode next;
 6  *     ListNode(int x) {
 7  *         val = x;
 8  *         next = null;
 9  *     }
10  * }
11  */
12 
13 
14 public class Solution {
15     /*
16      * @param node: a list node in the list
17      * @param x: An integer
18      * @return: the inserted new list node
19      */
20     public ListNode insert(ListNode node, int x) {
21         ListNode newNode = new ListNode(x);
22         if(node == null) {
23             newNode.next = newNode;
24             return newNode;
25         }
26         ListNode prev = node, curr = prev.next;
27         while(curr != node) {
28             if(curr.val > x && prev.val <= x) {
29                 break;
30             }
31             prev = curr;
32             curr = curr.next;
33         }
34         newNode.next = curr;
35         prev.next = newNode;
36         return node;
37     }
38 }

Related Problems

Insertion Sort List

原文地址:https://www.cnblogs.com/lz87/p/7496997.html