class Node { int data; Node next; Node(int d) { data = d; next = null; } } public class Test { static Node getIntersectionNode(Node headA, Node headB) { Node a = headA, b = headB; while (a != b) { a = (a == null) ? headB : a.next; b = (b == null) ? headA : b.next; } return a; } public static void main(String[] args) { Node common = new Node(8); common.next = new Node(10); Node headA = new Node(3); headA.next = new Node(7); headA.next.next = common; Node headB = new Node(99); headB.next = new Node(1); headB.next.next = common; Node intersection = getIntersectionNode(headA, headB); if (intersection != null) { System.out.println(intersection.data); } else { System.out.println("No intersection"); } } }
The code uses two pointers starting at each list head. When a pointer reaches the end, it switches to the other list's head. They meet at the intersection node with value 8.
Switching pointers makes both traverse the combined length of both lists, so they align at the intersection point or both reach null if no intersection.
class Node { int data; Node next; Node(int d) { data = d; next = null; } } public class Test { static Node getIntersectionNode(Node headA, Node headB) { Node a = headA, b = headB; while (a != b) { if (a == null && b == null) return null; if (a == null) a = headB; else a = a.next; if (b == null) b = headA; else b = b.next; } return a; } }
The code accesses a.next and b.next before checking if a or b is null, causing NullPointerException.
class Node { int data; Node next; Node(int d) { data = d; next = null; } } public class Test { static Node getIntersectionNode(Node headA, Node headB) { Node a = headA, b = headB; while (a != b) { a = (a == null) ? headB : a.next; b = (b == null) ? headA : b.next; } return a; } public static void main(String[] args) { Node headA = new Node(1); headA.next = new Node(2); headA.next.next = new Node(3); Node headB = new Node(4); headB.next = new Node(5); headB.next.next = new Node(6); Node intersection = getIntersectionNode(headA, headB); if (intersection != null) { System.out.println(intersection.data); } else { System.out.println("No intersection"); } } }
When no intersection exists, both pointers become null after traversing both lists, so the method returns null and prints "No intersection".
Each pointer traverses each list at most once, so total steps are proportional to sum of lengths.
