joshita / dev

Published

- 1 min read

Given 2 linkedlist find intersection of linked list

img of Given 2 linkedlist find intersection of linked list

Given two linked list if there is any intersection nodes

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

For example, the following two linked lists begin to intersect at node c1

           Node n5 = new Node(5, null);
        Node n4 = new Node(4, n5);
        Node n3 = new Node(3, n4);
        Node n2 = new Node(2, n3);
        Node n1 = new Node(1, n2);

        Node m3 = new Node(3, null);
        Node m2 = new Node(2, m3);
        Node m1 = new Node(1, m2);

   private Node intersectionOfLL(Node n1, Node n2) {
        HashSet<Node> set = new HashSet<>();
        Node node = n1;
        while (node != null) {
            set.add(node);
            node = node.next;
        }
        Node anotherNode = n2;
        while (anotherNode != null) {
            if(set.contains(anotherNode)) {
                return anotherNode;
            }
            anotherNode = anotherNode.next;
        }
        return null;
    }  

    public class Node {
        Node next ;
        int val ;
        Node(int v, Node n){
           this.next = n;
           this.val = v;
       }
    }