LeetCode 599 Insert into a Cyclic Sorted List (Java)

这篇博客介绍了如何在已排序的循环链表中插入一个值,保持链表的循环有序性。给出了具体的问题描述、注意事项、示例以及解决方案。
摘要由CSDN通过智能技术生成

[LintCode] 599 Insert into a Cyclic Sorted List 解题报告

Description

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

Given a list, and insert a value 4:
3->5->1
Return 5->1->3->4

Solution

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution{
    public ListNode insertIntoCycle(ListNode head,int val){
        if(head==null){
            head=new ListNode(val);
            head.next=head;
            return head;
        }
        ListNode cur1=head,cur2=head.next,newHead=head;
        while(cur2!=head){
            if(cur1.val>cur2.val){
                newHead=cur1;
                if(val>=newHead.val||val<=cur2.val){
                    break;
                }    
            }
            if(cur1.val<=val&&val<=cur2.val){
                break;
            }
            cur1=cur1.next;
            cur2=cur2.next;
        }
        head=new ListNode(val);
        head.next=cur2;
        cur1.next=head;
        if(val>newHead.val){
           return head; 
        }
        return newHead;
    }    
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值