MrainW's Home

All things come to those who wait!

0%

LeetCode 160. Intersection of Two Linked Lists

Question

Given the heads of two singly linked-lists headA and headB, return the node at which the two lists intersect. If the two linked lists have no intersection at all, return null.

https://leetcode.com/problems/intersection-of-two-linked-lists/

  • Solution1
1
2
3
4
5
6
7
8
9
10
public class Solution {
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;
}
}

Complexity:

Time complexity: O(n)

Space complexity: O(1)

Welcome to my other publishing channels