import
java.util.*;
public
class
GFG{
public
static
class
Node {
int
data;
Node next;
Node(
int
data)
{
this
.data = data;
this
.next =
null
;
}
public
Node() {
}
};
static
Node makeList(
int
n,
int
arr[])
{
Node h =
null
;
Node root =
new
Node();
for
(
int
i =
0
; i < n; i++) {
int
data = arr[i];
Node node =
new
Node(data);
if
(h ==
null
) {
h = node;
root = h;
}
else
{
root.next = node;
root = node;
}
}
return
h;
}
static
void
print_list(Node head)
{
while
(head !=
null
) {
System.out.print(head.data+
" "
);
head = head.next;
}
System.out.print(
"\n"
);
}
static
Node reverse(Node head)
{
Node current = head;
Node prev =
null
, next =
null
;
while
(current !=
null
) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
head = prev;
return
head;
}
static
Node findBreakPoint(Node head)
{
if
(head ==
null
) {
return
null
;
}
Node prev =
null
, curr = head;
while
(curr !=
null
) {
prev = curr;
curr = curr.next;
if
(curr !=
null
) {
if
((prev.data) <
0
&& (curr.data) >=
0
) {
return
prev;
}
}
}
curr = head;
while
(curr.next!=
null
) {
if
(curr.data <
0
) {
curr = curr.next;
continue
;
}
else
{
return
null
;
}
}
return
curr;
}
static
Node mergeUtil(Node h1,
Node h2)
{
if
(h1.next!=
null
) {
h1.next = h2;
return
h1;
}
Node curr1 = h1, next1 = h1.next;
Node curr2 = h2, next2 = h2.next;
while
(next1!=
null
&& curr2!=
null
) {
if
((curr2.data) >= (curr1.data)
&& (curr2.data) <= (next1.data)) {
next2 = curr2.next;
curr1.next = curr2;
curr2.next = next1;
curr1 = curr2;
curr2 = next2;
}
else
{
if
(next1.next!=
null
) {
next1 = next1.next;
curr1 = curr1.next;
}
else
{
next1.next = curr2;
return
h1;
}
}
}
return
h1;
}
static
Node merge(Node h1,
Node h2)
{
if
(h1==
null
)
return
h2;
if
(h2==
null
)
return
h1;
if
(h1.data < h2.data)
return
mergeUtil(h1, h2);
else
return
mergeUtil(h2, h1);
}
static
Node squaresList(Node head)
{
if
(head ==
null
)
return
null
;
Node mid = findBreakPoint(head);
Node temp = head;
while
(temp !=
null
) {
temp.data *= temp.data;
temp = temp.next;
}
if
(mid ==
null
) {
return
head;
}
Node h1 = head;
Node h2 = mid.next;
mid.next =
null
;
h1 = reverse(h1);
Node ans = merge(h1, h2);
return
ans;
}
public
static
void
main(String[] args)
{
int
n =
7
;
int
arr1[] = {
1
,
2
,
3
,
4
,
5
};
Node head = makeList(arr1.length,
arr1);
n =
6
;
int
arr2[] = { -
2
, -
1
,
0
,
1
,
2
};
head = makeList(arr2.length,
arr2);
int
arr3[] = { -
5
, -
4
, -
3
, -
2
, -
1
};
head = makeList(arr3.length,
arr3);
print_list(squaresList(head));
}
}