码迷,mamicode.com
首页 > 其他好文 > 详细

[LintCode] Insert into a Cyclic Sorted List

时间:2017-10-13 12:36:50      阅读:125      评论:0      收藏:0      [点我收藏+]

标签:amp   div   hat   cli   any   public   ted   tno   pre   

 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

[LintCode] Insert into a Cyclic Sorted List

标签:amp   div   hat   cli   any   public   ted   tno   pre   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!