-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
Copy path_708.java
53 lines (47 loc) · 1.53 KB
/
_708.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.fishercoder.solutions.firstthousand;
public class _708 {
static class Node {
public int val;
public Node next;
public Node(int val, Node next) {
this.val = val;
this.next = next;
}
public Node(int val) {
this.val = val;
}
public Node() {}
}
public static class Solution1 {
/*
* credit: https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list/solutions/995676/java-concise-o-n/
*/
public Node insert(Node head, int insertVal) {
Node insertNode = new Node(insertVal);
if (head == null) {
insertNode.next = insertNode;
return insertNode;
}
Node node = head;
while (node.next != head) {
if (node.val <= node.next.val) {
// increasing
if (node.val <= insertVal && insertVal <= node.next.val) {
// this is the place to insert
break;
}
} else {
// transition point, higher value to lower value
if (node.val < insertVal || insertVal < node.next.val) {
break;
}
}
node = node.next;
}
// insert this new node
insertNode.next = node.next;
node.next = insertNode;
return head;
}
}
}