LeetCode 599 Insert into a Cyclic Sorted List (Java)
程序员文章站
2022-05-20 10:57:38
...
[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;
}
}