1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
| /**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
ListNode a = headA, b = headB;
int cnta = 0, cntb = 0;
while (a != null && b != null) {
a = a.next;
b = b.next;
}
while (a != null || b != null) {
if (a != null) {
a = a.next;
cnta++;
}
if (b != null) {
b = b.next;
cntb++;
}
}
while (cnta > 0 || cntb > 0) {
if (cnta > 0) {
headA = headA.next;
cnta--;
}
if (cntb > 0) {
headB = headB.next;
cntb--;
}
}
while (headA != headB) {
headA = headA.next;
headB = headB.next;
}
return headA;
}
}
|