algorithm-base/animation-simulation/链表篇/剑指Offer52两个链表的第一个公共节点.md

93 lines
3.8 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

> **[tan45du_one](https://raw.githubusercontent.com/tan45du/tan45du.github.io/master/个人微信.15egrcgqd94w.jpg)** ,备注 github + 题目 + 问题 向我反馈
>
>
>
> <u>[****](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u> 两个平台同步,想要和题友一起刷题,互相监督的同学,可以在我的小屋点击<u>[**刷题小队**](https://raw.githubusercontent.com/tan45du/test/master/微信图片_20210320152235.2pthdebvh1c0.png)</u>进入。
#### [ Offer 52. ](https://leetcode-cn.com/problems/liang-ge-lian-biao-de-di-yi-ge-gong-gong-jie-dian-lcof/)
###
ACoffer
![image-20201029215837844](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/image-20201029215837844.7ezoerpghyk0.png)
HashSet
### HashSet
```java
public class Solution {
public ListNode getIntersectionNode (ListNode headA, ListNode headB) {
ListNode tempa = headA;
ListNode tempb = headB;
//定义hash表
HashSet<ListNode> arr = new HashSet<ListNode>();
while (tempa != null) {
arr.add(tempa);
tempa = tempa.next;
}
while (tempb != null) {
if (arr.contains(tempb)) {
return tempb;
}
tempb = tempb.next;
}
return tempb;
}
}
```
![](https://cdn.jsdelivr.net/gh/tan45du/photobed@master/photo/第一次相交的点.5nbxf5t3hgk0.gif)
```java
public class Solution {
public ListNode getIntersectionNode (ListNode headA, ListNode headB) {
//定义两个节点
ListNode tempa = headA;
ListNode tempb = headB;
//循环
while (tempa != tempb) {
//如果不为空就指针下移,为空就跳到另一链表的头部
tempa = tempa!=null ? tempa.next:headB;
tempb = tempb!=null ? tempb.next:headA;
}
return tempa;
}
}
```