Intersection of Two Linked Lists
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
if(headA == null || headB == null)
return null;
ListNode runA = headA, runB = headB;
while(runA != runB){
runA = (runA != null) ? runA.next : headB;
runB = (runB != null) ? runB.next : headA;
}
return runA;
}
}
Last updated