• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
neverlandly
博客园    首页    新随笔    联系   管理    订阅  订阅

Leetcode Articles: 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.

 

 

 

Solution:
Basically, you would have a loop that traverse the cyclic sorted list and find the point where you insert the value (Let’s assume the value being inserted called x). You would only need to consider the following three cases:

1. prev→val ≤ x ≤ current→val:

      Insert between prev and current.

2. x is the maximum or minimum value in the list:

 

Insert before the head. (ie, the head has the smallest value and its prev→val > head→val.

 

3. Traverses back to the starting point:

Insert before the starting point.

 

It's tricky to think of case 3: 

Q: What if the list has only one value?A:  Handled by case 3).

Q: What if the list is passed in as NULL?A: Then handle this special case by creating a new node pointing back to itself and return.

Q: What if the list contains all duplicates?A: Then it has been handled by case 3).

 

 1 public class Solution {
 2     public class ListNode {
 3         int val;
 4         ListNode next;
 5         ListNode(int x) {
 6             this.val = x;
 7             this.next = this;
 8         }
 9     }
10     
11     public ListNode rotateRight(ListNode start, int x) {
12         if (start == null) return new ListNode(x);
13         
14         ListNode cur = start;
15         while (true) {
16             if (cur.val < cur.next.val) {//没有到拐点
17                 if (x>=cur.val && x<=cur.next.val) {
18                     insert(cur, x);
19                     break;
20                 }
21                 else cur = cur.next;
22             }
23             else if (cur.val > cur.next.val) { //到了拐点
24                 if (x>=cur.val || x<=cur.next.val) {
25                     insert(cur, x);
26                     break;
27                 }
28                 else cur = cur.next;
29             }
30             else { //cur.val == cur.next.val
31                 if (cur.next == start) {
32                     insert(cur, x);
33                     break;
34                 }
35                 cur = cur.next;
36             }
37         }
38         return start;
39     }
40     
41     public void insert(ListNode cur, int x) {
42         ListNode node = new ListNode(x);
43         node.next = cur.next;
44         cur.next = node;
45     }
46 }

 

 
posted @ 2017-01-11 00:40  neverlandly  阅读(1632)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3