Intersection Point of 2 LinkedList
2 min readDec 4, 2020
Write a program to find the node at which the intersection of two singly linked lists begins. (Leetcode : 160)
class Node {int val;Node next;public Node() {}public Node(int val, Node next) {this.val = val;this.next = next;}}public class IntersectionPointOfLinkedLists {public static void main(String[] args) {Node node2 = new Node(10, new Node());Node node = new Node(3, new Node());node.next = new Node(6, new Node());node.next.next = new Node(9, new Node());node.next.next.next = new Node(15, new Node());node2.next = node.next.next.next;node.next.next.next.next = new Node(30, null);Node node = findIntersection(node, node2);
System.out.println(node.val);}public static Node findIntersection(Node node1, Node node2) {int len1 = getCount(node1);int len2 = getCount(node2);Node interSectionPoint = null;if (len1 > len2) {return interSectionPoint = getIntersection(node1, node2, len1 - len2);} else {return interSectionPoint = getIntersection(node2, node1, len2 - len1);}}public static int getIntersection(Node node1, Node node2, int d) {int count = 0;while (count != d) {node1 = node1.next;count++;}while (node1 != null && node2 != null) {if (node1 == node2) {return node1.val;} else {node1 = node1.next;node2 = node2.next;}}
return null;//throw new IllegalArgumentException();}public static int getCount(Node node) {int len = 0;while (node != null) {// System.out.print(node.val + " ");node = node.next;len++;}return len;}}
Thank you for reading!!