# Concise JAVA solution, O(1) memory O(n) time

• 1, Get the length of the two lists.

2, Align them to the same start point.

3, Move them together until finding the intersection point, or the end null

``````public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
while (lenA > lenB) {
lenA--;
}
while (lenA < lenB) {
lenB--;
}
// find the intersection until end
}
}

private int length(ListNode node) {
int length = 0;
while (node != null) {
node = node.next;
length++;
}
return length;
}``````

• it`s a good answer~~but the running time is O(n+m+max[n.m]), right? I tried this in python, somehow it got better running time than two pointer solution

• Thats a perfect solution,thanks :)

• what is the two pointer solution?

• We have the same ideas! Even how we use two while loops to align the lists! I think this solution is great.

• Possible null pointer exception if two linked list do not have intersection.

• This post is deleted!

• @tethys it will return 4. in the code line

the two nodes will be equal when they have the same address (not the same stored value)

• Hi @jimmydada, what is the two pointer solution?

• so this solution make mistakes?

• no, it's correct. You can have a try using the OJ. The example discussed above is a wrong example. if two links are 1-2-3-4 and 2-5-4, return 2 is correct.

• what if the two lists have more than one intersections? Shouldn't we find out all of them?

• You have a misunderstanding about the O(n) time. If a program runs in O(n) time, it does not mean it's running time equals to n. It means the running time equals to (an+b), where a and b can be any real numbers.
Hope this helps you.
If I make any mistakes, welcome to point out.

• if the two linked list is:
1,2,3,4,5 and
3,7,5
it's will not work!

• the definition of the intersection is a bit confusing ...

• what if 1 2 3 4 and 2 3 4 5, we should return 2, but this will not

But why
can not work?

• Very concise and intuitive! Better than tricky approach!