import java.io.*;
import java.util.*;
class GFG {
static void printList(Node node)
{
while (node != null) {
System.out.print(node.data+" ");
node = node.next;
}
}
static void storeEle(Node head1, Node head2,Map<Integer, Integer> eleOcc)
{
Node ptr1 = head1;
Node ptr2 = head2;
while (ptr1 != null || ptr2 != null) {
if (ptr1 != null) {
if(eleOcc.get(ptr1.data)==null){
eleOcc.put(ptr1.data,1);
}else{
eleOcc.put(ptr1.data,eleOcc.get(ptr1.data)+1);
}
ptr1 = ptr1.next;
}
if (ptr2 != null) {
if(eleOcc.get(ptr2.data)==null){
eleOcc.put(ptr2.data,1);
}else{
eleOcc.put(ptr2.data,eleOcc.get(ptr2.data)+1);
}
ptr2 = ptr2.next;
}
}
}
static Node getUnion(Map<Integer, Integer> eleOcc)
{
Node result = null;
for (int key:eleOcc.keySet()){
Node node = new Node(key);
node.next=result;
result=node;
}
return result;
}
static void printUnionIntersection(Node head1,Node head2)
{
Map<Integer, Integer> eleOcc = new HashMap<>();
storeEle(head1, head2, eleOcc);
Node intersection_list = getIntersection(eleOcc);
Node union_list = getUnion(eleOcc);
System.out.println("\nIntersection list is: ");
printList(intersection_list);
System.out.println("\nUnion list is: ");
printList(union_list);
}
static Node getIntersection(Map<Integer, Integer> eleOcc)
{
Node result = null;
for (int key:eleOcc.keySet()){
if(eleOcc.get(key)==2){
Node node = new Node(key);
node.next=result;
result=node;
}
}
return result;
}
public static void main (String[] args) {
LinkedList l1 = new LinkedList();
LinkedList l2 = new LinkedList();
l1.push(1);
l1.push(2);
l1.push(3);
l1.push(4);
l1.push(5);
l2.push(1);
l2.push(3);
l2.push(5);
l2.push(6);
System.out.print("First List: \n");
printList(l1.head);
System.out.println("\nSecond List: ");
printList(l2.head);
printUnionIntersection(l1.head, l2.head);
}
}
class Node{
int data;
Node next;
Node(int d){
this.data=d;
}
}
class LinkedList{
Node head;
void push(int new_data){
Node new_node = new Node(new_data);
new_node.next = head;
head=new_node;
}
}