import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.List;
class
Node {
int
val;
Node next;
Node(
int
x) {
val = x;
next =
null
;
}
}
public
class
MoveKthLargestFibonacciNode {
static
Node moveKthLargestFibonacciNode(Node head,
int
K) {
List<Integer> fibonacciNumbers =
new
ArrayList<>();
Node current = head;
while
(current !=
null
) {
int
val = current.val;
int
a =
0
, b =
1
;
while
(b <= val) {
if
(b == val) {
fibonacciNumbers.add(val);
break
;
}
int
temp = b;
b = a + b;
a = temp;
}
current = current.next;
}
if
(fibonacciNumbers.size() < K) {
return
head;
}
Collections.sort(fibonacciNumbers, Collections.reverseOrder());
int
kthLargestFibonacci = fibonacciNumbers.get(K -
1
);
current = head;
Node prev =
null
;
while
(current !=
null
) {
if
(current.val == kthLargestFibonacci) {
if
(prev !=
null
) {
prev.next = current.next;
current.next =
null
;
}
else
{
head = current.next;
}
break
;
}
prev = current;
current = current.next;
}
if
(current !=
null
) {
current = head;
if
(current ==
null
) {
head = prev = current =
new
Node(kthLargestFibonacci);
}
else
{
while
(current.next !=
null
) {
current = current.next;
}
current.next =
new
Node(kthLargestFibonacci);
}
}
return
head;
}
static
void
printList(Node head) {
Node current = head;
while
(current !=
null
) {
System.out.print(current.val +
" -> "
);
current = current.next;
}
System.out.println(
"NULL"
);
}
public
static
void
main(String[] args) {
Node head1 =
new
Node(
12
);
head1.next =
new
Node(
11
);
head1.next.next =
new
Node(
0
);
head1.next.next.next =
new
Node(
5
);
head1.next.next.next.next =
new
Node(
8
);
head1.next.next.next.next.next =
new
Node(
13
);
head1.next.next.next.next.next.next =
new
Node(
17
);
head1.next.next.next.next.next.next.next =
new
Node(
21
);
int
K1 =
3
;
head1 = moveKthLargestFibonacciNode(head1, K1);
printList(head1);
Node head2 =
new
Node(
5
);
head2.next =
new
Node(
4
);
head2.next.next =
new
Node(
34
);
head2.next.next.next =
new
Node(
25
);
head2.next.next.next.next =
new
Node(
1
);
int
K2 =
2
;
head2 = moveKthLargestFibonacciNode(head2, K2);
printList(head2);
}
}