# Memory Limit Exceeded But I almost didn't allocate any new memory.

• Here is my code. The idea is there are 3 length in the intersected list:

• x - the length in the list started with headA before the intersect point
• y - the length after the intersect point
• z - the length in the list started with headB before the intersect point

By iterating from headA we can get:
x + y = m

By iterating from headB we can get:
z + y = n

Reverse list started with headB and iterate from headA we can get:
x + z = q

We can easily solve this equation:
x = (m - n + q) / 2

And finally we can get the intersect node.

However it's Memory Limit Exceeded. I don't understand why.

``````class Solution {
public:
int len = 0;
while (cur != NULL) {
cur = cur->next;
len++;
}
return len;
}

ListNode * reverse(ListNode * head) {
while (cur != NULL) {
ListNode * next = cur->next;
cur->next = prev;
prev = cur;
cur = next;
}
return prev;
}

ListNode * getTail(ListNode * head) {
while (cur != NULL) {
prev = cur;
cur = cur->next;
}
return prev;
}

// if n is 0, return the first node
ListNode * getNthNode(ListNode * head, int n) {
while (n > 0) {
cur = cur->next;
n--;
}
return cur;
}

if (tailA != headB) return NULL; // no intersection;