-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlc-160.java
More file actions
50 lines (49 loc) · 1.27 KB
/
lc-160.java
File metadata and controls
50 lines (49 loc) · 1.27 KB
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
/**
* 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) {
if(headA == null || headB == null)return null;
int alen = 0, blen = 0;
ListNode ca = headA, cb = headB;
while(ca != null || cb != null) {
if(ca != null) {
alen++;
ca = ca.next;
}
if(cb != null) {
blen++;
cb = cb.next;
}
}
ca = headA;
cb = headB;
if(alen > blen) {
while(alen > blen) {
//让a链表先走,使得起步时步数一致
alen--;
ca = ca.next;
}
}else if(alen < blen){
while(alen < blen) {
//让b链表先走,使得起步时步数一致
blen--;
cb = cb.next;
}
}
while(ca != null && cb != null) {
if(ca == cb) return ca;
ca = ca.next;
cb = cb.next;
}
return null;
}
}