[LintCode] Insert into a Cyclic Sorted List
Posted Push your limit!
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了[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
以上是关于[LintCode] Insert into a Cyclic Sorted List的主要内容,如果未能解决你的问题,请参考以下文章
lintcode-easy-Insert Node in a Binary Search Tree
[LintCode] Insert Node in a Binary Search Tree