Intersection of Two Linked Lists LeetCode solution in Java

1
public class Solution {
2
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
3
ListNode tempA = headA, tempB = headB;
4
int lenA = 0, lenB = 0;
5
while (tempA != null) {
6
lenA++;
7
tempA = tempA.next;
8
}
9
while (tempB != null) {
10
lenB++;
11
tempB = tempB.next;
12
}
13
tempA = headA;
14
tempB = headB;
15
if (lenB > lenA) {
16
for (int i = 0; i < lenB - lenA; i++) {
17
tempB = tempB.next;
18
}
19
} else if (lenA > lenB) {
20
for (int i = 0; i < lenA - lenB; i++) {
21
tempA = tempA.next;
22
}
23
}
24
while (tempA != null && tempA != tempB) {
25
tempA = tempA.next;
26
tempB = tempB.next;
27
}
28
return tempA;
29
}
30
}

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0