Skip to content

Commit e49c63b

Browse files
committed
优化160
1 parent 9a9aa1a commit e49c63b

File tree

1 file changed

+5
-26
lines changed

1 file changed

+5
-26
lines changed
Lines changed: 5 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,42 +1,21 @@
11
package com.diguage.algo.leetcode;
22

33
import com.diguage.algo.util.ListNode;
4-
import com.diguage.util.ListNodes;
5-
6-
import java.util.Objects;
74

85
public class _0160_IntersectionOfTwoLinkedLists_4 {
96
// tag::answer[]
7+
108
/**
119
* @author D瓜哥 · https://www.diguage.com
1210
* @since 2025-10-30 21:33:00
1311
*/
1412
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
1513
ListNode ha = headA, hb = headB;
16-
boolean fa = true, fb = true; // 如果不加标注,则会陷入死循环。
17-
while (ha != null && hb != null) {
18-
if (Objects.equals(ha, hb)) {
19-
return ha;
20-
}
21-
ha = ha.next;
22-
hb = hb.next;
23-
if (fa && Objects.isNull(ha)) {
24-
ha = headB;
25-
fa = false;
26-
}
27-
if (fb && Objects.isNull(hb)) {
28-
hb = headA;
29-
fb = false;
30-
}
14+
while (ha != hb) { // 如果不相交,则最后都会走到 null,也会退出循环
15+
ha = ha == null ? headB : ha.next;
16+
hb = hb == null ? headA : hb.next;
3117
}
32-
return null;
18+
return ha;
3319
}
34-
3520
// end::answer[]
36-
public static void main(String[] args) {
37-
new _0160_IntersectionOfTwoLinkedLists_4()
38-
.getIntersectionNode(
39-
ListNodes.build(4, 1, 8, 4, 5),
40-
ListNodes.build(5, 6, 1, 8, 4, 5));
41-
}
4221
}

0 commit comments

Comments
 (0)