Insert into a Cyclic Sorted List

来源:互联网 发布:tv007网络电视在线直播 编辑:程序博客网 时间:2024/05/19 17:23

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.

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) {        if (node == null) {            node = new ListNode(x);            node.next = node;            return node;        }        ListNode point = node;        ListNode prev = null;        //循环一个周期        do {            prev = point;            point = point.next;            if (prev.val <= x && point.val >= x) {                break;            }            if ((prev.val > point.val) && (x > prev.val || x < point.val)) {                break;            }        } while (point != node);        ListNode newNode = new ListNode(x);        newNode.next = point;        prev.next = newNode;        return newNode;    }}
0 0
原创粉丝点击