import
java.util.ArrayList;
import
java.util.Collections;
import
java.util.List;
class
Node {
int
data;
Node next;
public
Node(
int
val) {
data = val;
next =
null
;
}
}
public
class
MergeAndSortLinkedLists {
static
Node insertNode(Node head,
int
x) {
Node ptr =
new
Node(x);
if
(head ==
null
) {
head = ptr;
}
else
{
Node temp = head;
while
(temp.next !=
null
) {
temp = temp.next;
}
temp.next = ptr;
}
return
head;
}
static
void
display(Node head) {
if
(head ==
null
) {
System.out.println(
"NULL"
);
}
else
{
while
(head !=
null
) {
System.out.print(head.data);
if
(head.next !=
null
) {
System.out.print(
"->"
);
}
head = head.next;
}
System.out.println();
}
}
static
Node mergeLinkedList(Node head1, Node head2) {
if
(head1 ==
null
) {
return
head2;
}
Node ptr = head1;
while
(ptr.next !=
null
) {
ptr = ptr.next;
}
ptr.next = head2;
return
head1;
}
static
void
sortLinkedList(Node head1, Node head2) {
head1 = mergeLinkedList(head1, head2);
if
(head1 ==
null
) {
System.out.println(
"Empty List"
);
return
;
}
List<Integer> list =
new
ArrayList<>();
Node current = head1;
while
(current !=
null
) {
list.add(current.data);
current = current.next;
}
Collections.sort(list);
current = head1;
for
(
int
i =
0
; i < list.size(); i++) {
current.data = list.get(i);
current = current.next;
}
display(head1);
}
public
static
void
main(String[] args) {
Node head1 =
null
;
head1 = insertNode(head1,
3
);
head1 = insertNode(head1,
5
);
head1 = insertNode(head1,
1
);
Node head2 =
null
;
head2 = insertNode(head2,
6
);
head2 = insertNode(head2,
2
);
head2 = insertNode(head2,
4
);
head2 = insertNode(head2,
9
);
sortLinkedList(head1, head2);
}
}