-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathInsertToCircularLinkedList.java
39 lines (38 loc) · 1.27 KB
/
InsertToCircularLinkedList.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
package main.java.topcodingquestion.linkedlist;
//https://leetcode.com/problems/insert-into-a-sorted-circular-linked-list/
public class InsertToCircularLinkedList {
public Node insert(Node head, int insertVal) {
if (head == null) {
Node temp = new Node(insertVal);
temp.next = temp;
return temp;
}
Node prev = head, curr = head.next;
boolean isInsert = false;
while (true) {
if (prev.val <= insertVal && insertVal <= curr.val) {
//Case 1
isInsert = true;
} else if (prev.val > curr.val) {
//Case 2
// where we locate the tail element
// 'prev' points to the tail, i.e. the largest element!
if (insertVal >= prev.val || insertVal <= curr.val) {
isInsert = true;
}
}
if (isInsert) {
prev.next = new Node(insertVal, curr);
return head;
}
prev = curr;
curr = curr.next;
if (prev == head)
break;
}
//Case #3.
//did not insert the node in the loop
prev.next = new Node(insertVal, curr);
return head;
}
}