import java.util.*;
class Node {
public int data;
public Node next;
Node(int d) {
data = d;
next = null;
}
}
class Solution {
// This function gets two arguments - the head pointers of the two linked lists
// Return the node which is the intersection point of these linked lists
// It is assured that the two lists intersect
Node intersectionOfTwoLinkedLists(Node l1, Node l2) {
int n = 0 , m = 0;
Node p1 = l1, p2 = l2;
while(p1 != null){
p1 = p1.next;
n++;
}
while(p2 != null){
p2 = p1.next;
m++;
}
if(n>m){
Node x1 = l1 , x2 = l2;
int k = n-m;
for(int i = 1; i<= k;i++){
x1 = x1.next;
}
while(x1 != null && x2 != null){
if(x1.data == x2.data){
return x1;
}
x1 = x1.next;
x2 = x2.next;
}
}else if(m>n){
Node x1 = l1 , x2 = l2;
int k = m-n;
for(int i = 1; i<= k;i++){
x2 = x2.next;
}
while(x1 != null && x2 != null){
if(x1.data == x2.data){
return x1;
}
x1 = x1.next;
x2 = x2.next;
}
}else{
Node x1 = l1 , x2 = l2;
while(x1 != null && x2 != null){
if(x1.data == x2.data){
return x1;
}
x1 = x1.next;
x2 = x2.next;
}
}
return null;
}
}
public class Main {
static Scanner sc = new Scanner(System.in);
public static Node buildList(HashMap<Integer, Node> hash) {
int x = sc.nextInt();
Node head = new Node(x);
Node current = head;
hash.put(x, head);
while (x != -1) {
x = sc.nextInt();
if (x == -1)
break;
Node n = new Node(x);
hash.put(x, n);
current.next = n;
current = n;
}
current.next = null;
return head;
}
public static void printLinkedList(Node head) {
Node temp = head;
while (temp != null) {
System.out.print(temp.data + " ");
temp = temp.next;
}
System.out.println();
}
public static void main(String[] args) {
HashMap<Integer, Node> hash = new HashMap<Integer, Node>();
Node l1 = buildList(hash);
Node l2 = null;
int x = sc.nextInt();
l2 = new Node(x);
Node temp = l2;
while (x != -1) {
x = sc.nextInt();
if (x == -1)
break;
if (hash.containsKey(x)) {
temp.next = hash.get(x);
break;
}
Node n = new Node(x);
temp.next = n;
temp = n;
}
System.out.print("L1 - ");
printLinkedList(l1);
System.out.print("L2 - ");
printLinkedList(l2);
Solution s = new Solution();
Node intersectionPoint = s.intersectionOfTwoLinkedLists(l1, l2);
System.out.println("Intersection at node with data = " + intersectionPoint.data);
}
}
--------what’s the error in this code, i have also used the same approach used in the hint video for this problem