题目地址:https://leetcode.cn/problems/intersection-of-two-linked-lists/
思路一:辅助空间法。引入一个HashMap,遍历其中一个链表的所有节点,并将节点本身作为key存入HashMap。再遍历另一个链表的所有节点,如果节点已经在HashMap中存在,说明有相交,返回该节点;否则返回null。代码如下:
public class Solution {
public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
//构建用于存放headA所有节点的Hash表
HashMap<ListNode, Integer> aNodes = new HashMap<ListNode, Integer>();
while(headA != null) {
aNodes.put(headA, 1);
headA = headA.next;
}
//遍历headB找到headA中的节点就返回
while(headB != null) {
if(null != aNodes.get(headB)) {
return he