Algo-Sim › Linked Lists

Intersection of Two Linked Lists

Easy · Linked Lists · step through it in Java, Python and C++ on your own input

Two pointers that restart on the other list when they fall off the end both walk m + n nodes and meet on the first shared node.

Problem

Two singly linked lists start at headA and headB. They may merge at some node and share every node from there on (the same nodes, not copies with equal values). Return the first shared node, or null if the lists never meet. Neither list may be changed, and there are no cycles.

Constraints

Edge cases to test

Follow-up questions

Why do the pointers meet?
Each walks a + c + b nodes in total (its own part, the shared part, the other’s part), so they line up on the first shared node or on null.
What is the length-based alternative?
Compute both lengths, advance the longer list by the difference, then walk together: same O(m + n), O(1).

Solution

Java

public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
    ListNode a = headA, b = headB;
    while (a != b) {
        a = (a == null) ? headB : a.next;
        b = (b == null) ? headA : b.next;
    }
    return a;
}

Python

def get_intersection_node(headA, headB):
    a, b = headA, headB
    while a is not b:
        a = headB if a is None else a.next
        b = headA if b is None else b.next
    return a

C++

#include <bits/stdc++.h>
using namespace std;

class Solution {
  public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode *a = headA, *b = headB;
        while (a != b) {
            a = (a == nullptr) ? headB : a->next;
            b = (b == nullptr) ? headA : b->next;
        }
        return a;
    }
};

More Linked Lists problems