题目:
https://leetcode-cn.com/problems/intersection-of-two-linked-lists/
import java.util.HashMap; import java.util.HashSet; public class _160_GetIntersectionNode { // 哈希集合 public ListNode getIntersectionNode(ListNode headA, ListNode headB) { HashSet<ListNode> set = new HashSet<>(); ListNode la = headA; ListNode lb = headB; while (la != null) { set.add(la); la = la.next; } while (lb != null) { if (set.contains(lb)) { return lb; } else set.add(lb); lb = lb.next; } return null; } // 双指针法 public ListNode getIntersectionNode1(ListNode headA, ListNode headB) { if (headA == null || headB == null) { return null; } ListNode la = headA; ListNode lb = headB; while (la != lb) { la = la == null ? headB : la.next; lb = lb == null ? headA : lb.next; } return la; } }