剑指 Offer 52. 两个链表的第一个公共节点
简单题
分别遍历链表,先遍历链表A,使用哈希表存储节点,再遍历链表B,查找公共节点
import java.util.HashSet;
import java.util.Set;
/**
* 剑指 Offer 52. 两个链表的第一个公共节点
*
*/
public class SolutionJZ52 {
public class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
next = null;
}
}
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
Set<ListNode> nodeSet = new HashSet<>();
while (headA != null) {
nodeSet.add(headA);
headA = headA.next;
}
while (headB != null) {
if (nodeSet.contains(headB)) {
return headB;
}
headB = headB.next;
}
return null;
}
}