• [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

  • 相关阅读:
    前后端反爬虫的一些奇怪姿势【转载】
    Scrapy 中常用的中间件和管道组件
    Jquery各个版本的区别
    userAgent
    操作系统
    手机类别
    移动端设备UA检测
    iPhone6的CSS3媒体查询
    所有设备的CSS像素
    解读所有设备的css像素的网站
  • 原文地址:https://www.cnblogs.com/lz87/p/7496997.html
Copyright © 2020-2023  润新知