LinkedList getIntersection(Node head1, Node head2) { HashSet<Integer> hset = new HashSet<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); while (n1 != null) { if (hset.contains(n1.data)) hset.add(n1.data); else hset.add(n1.data); n1 = n1.next; } while (n2 != null) { if (hset.contains(n2.data)) result.push(n2.data); n2 = n2.next; } return result; } LinkedList getUnion(Node head1, Node head2){ HashMap<Integer, Integer> hmap = new HashMap<>(); Node n1 = head1; Node n2 = head2; LinkedList result = new LinkedList(); while (n1 != null) { if (hmap.containsKey(n1.data)) { int val = hmap.get(n1.data); hmap.put(n1.data, val + 1); } else hmap.put(n1.data, 1); n1 = n1.next; } while (n2 != null) { if (hmap.containsKey(n2.data)) { int val = hmap.get(n2.data); hmap.put(n2.data, val + 1); } else hmap.put(n2.data, 1); n2 = n2.next; } for (int a : hmap.keySet()) result.append(a); return result; }