# Intersection of Two Linked Lists Problem & Solution

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.

## C++ Solution

The runtime complexity of the algorithm is \$O(n + m)\$.

``````#pragma GCC optimize("Ofast")
#pragma GCC optimization("unroll-loops")

static const int _=[](){std::ios::sync_with_stdio(false);cin.tie(nullptr);cout.tie(nullptr);return 0;}();

/**
* struct ListNode {
*   int val;
*   ListNode *next;
*   ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
int lenA = 0;
while (cursorA != nullptr) {
cursorA = cursorA->next;
++lenA;
}

int lenB = 0;
while (cursorB != nullptr) {
cursorB = cursorB->next;
++lenB;
}

while (lenA > lenB) {
--lenA;
}

while (lenB > lenA) {
--lenB;
}

// At this step, `lenA == lenB`.
while (lenA > 0) {
}

--lenA;
}

return nullptr;
}
};
``````

## Start Here

Many paths, there are. Follow yours, you must.