Finding the node at which the intersection of two singly linked lists begins using the Two Pointers technique.
The original problem is here.
None (null object in Java).# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
map_a = {}
node_a_now = headA
while node_a_now:
map_a[node_a_now] = True
node_a_now = node_a_now.next
node_b_now = headB
while node_b_now:
if node_b_now in map_a:
return node_b_now
node_b_now = node_b_now.next
return None
pA and pB, pointing to headA and headB respectively.pA reaches the end of list A, redirect it to the head of list B.pB reaches the end of list B, redirect it to the head of list A.pA and pB will eventually meet at the intersection node. For simplicity of the algrithm, do not stop at the first intersection because to do that we need to check the intersection at every step. Rather, just go on to the end and return the last node on intersection.None. The loop will terminate, and we can safely return None.# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
if not headA or not headB:
return None
pA, pB = headA, headB
while pA != pB:
# If pointer reaches the end, switch to the other list's head
# Otherwise, move to the next node
pA = pA.next if pA else headB
pB = pB.next if pB else headA
return pA
pA and pB), which requires constant extra space regardless of the size of the linked lists.None.