import
java.util.*;
class
Node {
int
data;
Node next;
public
Node(
int
data)
{
this
.data = data;
next =
null
;
}
}
class
GfG {
public
static
void
changeTwoBefore0(Node head)
{
if
(head ==
null
|| head.next ==
null
|| head.next.next ==
null
)
return
;
if
((head.data == head.next.data)
&& (head.next.next.data ==
0
)) {
int
temp = head.data;
head.data =
2
* temp;
head.next.data =
0
;
if
(head.next.next.next !=
null
)
head = head.next.next.next;
else
return
;
}
else
head = head.next;
changeTwoBefore0(head);
}
public
static
Node appendZero(Node head)
{
if
(head ==
null
|| head.next ==
null
)
return
head;
Node tail = head;
while
(tail.next !=
null
)
tail = tail.next;
Node origTail = tail;
Node curr = head;
while
(curr.next !=
null
&& curr.data ==
0
) {
tail.next = curr;
tail = curr;
curr = curr.next;
}
head = curr;
Node prev = curr;
curr = curr.next;
while
(curr != origTail) {
if
(curr.data ==
0
) {
tail.next = curr;
tail = curr;
prev.next = curr.next;
}
else
prev = curr;
curr = curr.next;
}
tail.next =
null
;
return
head;
}
public
static
Node doubleAndAppend0(Node head)
{
changeTwoBefore0(head);
return
appendZero(head);
}
public
static
void
display(Node head)
{
while
(head !=
null
) {
System.out.print(head.data +
" -> "
);
head = head.next;
}
}
public
static
void
main(String[] args)
{
Node head =
new
Node(
4
);
head.next =
new
Node(
4
);
head.next.next =
new
Node(
0
);
head.next.next.next =
new
Node(
2
);
head.next.next.next.next =
new
Node(
3
);
head.next.next.next.next.next =
new
Node(
4
);
head.next.next.next.next.next.next =
new
Node(
3
);
head.next.next.next.next.next.next.next
=
new
Node(
3
);
head.next.next.next.next.next.next.next.next
=
new
Node(
0
);
head.next.next.next.next.next.next.next.next.next
=
new
Node(
4
);
System.out.println(
"Original linked list :"
);
display(head);
head = doubleAndAppend0(head);
System.out.println(
"\nModified linked list :"
);
display(head);
}
}