Intersection of Two Linked Lists
1 approach, code in every language
Problem description
You are given the heads of two singly linked lists. Return the exact node at which the two lists first join together, or return null if they never meet.
Intersection is defined by reference, not by value: the two lists share the same physical node object from the meeting point onward, so their tails are identical. The original list structures must be left unchanged.
Example 1
Input: listA = [4,1,8,4,5], listB = [5,6,1,8,4,5], skipA = 2, skipB = 3
Output: Reference of the node with value 8
Both lists lead into the same node valued 8 and share every node after it, so that node is the intersection.
Example 2
Input: listA = [2,6,4], listB = [1,5]
Output: null
The two lists have no node in common, so the answer is null.
Constraints
The number of nodes of listA is in the range [1, 3 * 10^4].The number of nodes of listB is in the range [1, 3 * 10^4].1 <= Node.val <= 10^5The two lists either intersect at exactly one node or do not intersect at all.
Create a free account to see the solution
You get the step-by-step animation, the intuition and clean code in every language. Free, no credit card.
After the pattern
Now solve one you haven't seen.
Reading a pattern isn't the same as using it. The practice set has 1,194 original problems on the same techniques, each graded in your browser.
1,194 problems · 15,062 graded tests · free