15 Jun 2024C++ / Python / TypeScriptEasy

Intersection of Two Linked Lists

Collected C++, Python, TypeScript solutions for intersection of two linked lists. Add a dedicated write-up later if you want deeper notes.

auto-generated entry for Intersection of Two Linked Lists. the solution files are available below.

solution files

  • C++ intersection-of-two-linked-lists/synced-solution.cpp
  • Python intersection-of-two-linked-lists/synced-solution.py
  • TypeScript intersection-of-two-linked-lists/synced-solution.ts

Solution files

Pythonintersection-of-two-linked-lists/synced-solution.py
class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        a = headA
        b = headB
        while a != b:
            a = a.next if a else headB
            b = b.next if b else headA
        return a
C++intersection-of-two-linked-lists/synced-solution.cpp
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* a = headA;
        ListNode* b = headB;
        while (a != b) {
            a = a ? a->next : headB;
            b = b ? b->next : headA;
        }
        return a;
    }
};
TypeScriptintersection-of-two-linked-lists/synced-solution.ts
function getIntersectionNode(headA: ListNode | null, headB: ListNode | null): ListNode | null {
    let a = headA;
    let b = headB;
    while (a !== b) {
        a = a ? a.next : headB;
        b = b ? b.next : headA;
    }
    return a;
}