相交链表
2026年3月24日小于 1 分钟
相交链表
使用的方法
HashSet:使用一个哈希集合来存储链表 A 的节点,然后遍历链表 B,检查是否有节点在集合中出现过。
解题思路
- 首先,创建一个空的哈希集合
set。 - 遍历链表 A,将每个节点添加到集合
set中。 - 然后,遍历链表 B,对于每个节点,检查它是否在集合
set中。如果找到了一个节点在集合中出现过,说明这个节点就是两个链表的交点,返回这个节点。 - 如果遍历完链表 B 后没有找到任何节点在集合中出现过,说明两个链表没有交点,返回
null。
代码实现
/**
* 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) {
Set<ListNode> set= new HashSet<>();
ListNode current = headA;
while (current != null) {
set.add(current);
current = current.next;
}
current = headB;
while (current != null) {
if (set.contains(current)) {
return current;
}
current = current.next;
}
return null;
}
}