Leetcode 160. Intersection of Two Linked Lists
The problem is to determine the node at which two singly linked lists intersect. If the two linked lists have no intersection at all, return null.
Definition for singly-linked list:
class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
Given heads for two singly linked lists headA
and headB
, return the node at which the two lists intersect. If there is no intersection, return null.
Example:
Input: intersectVal = 8, listA = [4,1,8,4,5], listB = [5,6,1,8,4,5]
Output: Intersected at '8'
Explanation: The intersected node's value is 8 (note that this must be the same node, not two nodes with the same value).
Q: What can we assume about the input linked lists? A: You can assume the lists are non-cyclical and may have different lengths.
Q: What should we return if there is no intersection?
A: Return null
.
To solve this problem, we can use the following approach:
This method works because once both lists are aligned at the same starting point relative to their ends, any intersection will be detected as both lists are traversed together.
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if (headA == null || headB == null) return null;
// Get the length of both lists
int lengthA = getLength(headA);
int lengthB = getLength(headB);
// Align heads
if (lengthA > lengthB) {
headA = moveForward(headA, lengthA - lengthB);
} else if (lengthB > lengthA) {
headB = moveForward(headB, lengthB - lengthA);
}
// Traverse both lists and find the intersection
while (headA != null && headB != null) {
if (headA == headB) {
return headA;
}
headA = headA.next;
headB = headB.next;
}
return null;
}
private int getLength(ListNode head) {
int length = 0;
while (head != null) {
length++;
head = head.next;
}
return length;
}
private ListNode moveForward(ListNode head, int steps) {
while (steps > 0 && head != null) {
head = head.next;
steps--;
}
return head;
}
}
This solution effectively adjusts the starts of the lists to ensure any intersection is found efficiently.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?