Insert into a Cyclic Sorted List
来源:互联网 发布:iphone翻墙用什么软件 编辑:程序博客网 时间:2024/05/28 09:31
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.
Notice
3->5->1
is a cyclic list, so 3
is next node of 1
.3->5->1
is same with 5->1->3
Example
python
Given a list, and insert a value 4
:3->5->1
Return 5->1->3->4
java
/** * Definition for ListNode * public class ListNode { * int val; * ListNode next; * ListNode(int x) { * val = x; * next = null; * } * } */public class Solution { /* * @param node: a list node in the list * @param x: An integer * @return: the inserted new list node */ public ListNode insert(ListNode node, int x) { // write your code here ListNode n = new ListNode(x); if (node == null) { n.next = n; return n; } ListNode curr = node.next; ListNode prev = node; while (curr != node) { if (prev.val <= x && curr.val >= x) { break; } if (prev.val > curr.val && (prev.val < x || curr.val > x)) { break; } curr = curr.next; prev = prev.next; } prev.next = n; n.next = curr; return node; }}
python
"""Definition of ListNodeclass ListNode(object): def __init__(self, val, next=None): self.val = val self.next = next"""class Solution: """ @param: node: a list node in the list @param: x: An integer @return: the inserted new list node """ def insert(self, node, x): # write your code here n = ListNode(x) if node is None: n.next = n return n prev, curr = node, node.next while curr != node: if prev.val <= x and curr.val >= x: break if prev.val > curr.val and (prev.val < x or curr.val > x): break curr, prev = curr.next, prev.next prev.next = n n.next = curr return node
阅读全文
0 0
- Insert into a Cyclic Sorted List
- Insert into a Cyclic Sorted List
- Insert into a Cyclic Sorted List
- Insert into a Cyclic Sorted List
- Insert into a Cyclic Sorted List
- 【Hackerrank】Insert a node into a sorted doubly linked list
- Insert in a sorted list
- Insert into a sorted circular linked list 环状链表 插入节点
- Python pandas insert list into a cell
- demo for insert values into sorted single list
- Insert Data into Sorted Table
- Insert Data into Sorted Table
- Insert a node in a sorted linked list.
- P21 (*) Insert an element at a given position into a list.
- P20 (*) P21 (*)Remove the Kth element from a list;Insert an element at a given position into a list.
- jquery insert a table into div
- 代码面试题:Insert Sorted Linked List
- Sorted insert for circular linked list
- 7-26 Harry Potter's Exam(25 point(s))(Floyd算法)
- tensorFlow运行错误解决汇总
- 头条项目总结
- linux jdk1.8
- Linux上定时任务发布及锁定(1)
- Insert into a Cyclic Sorted List
- Air系列模块驱动lcd显示
- ROS中四元素欧拉角变换
- 类型别名
- JavaShowAlgorithm-Median of Two Sorted Arrays
- 深度学习-note-RNN(循环神经网络)
- python 中 os 和 sys 的区别和联系
- 第二章 SQL命令参考-ROLLBACK
- 属性getter和setter