package linkedlist; import java.util.HashSet; /** * 题目:160. 相交链表 (getIntersectionNode) * 描述:给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表不存在相交节点,返回 null 。 * 链接:https://leetcode.cn/problems/intersection-of-two-linked-lists/ */ //没想出高效方法 public class GetIntersectionNode { public ListNode getIntersectionNode(ListNode headA, ListNode headB) { HashSet visited = new HashSet(); ListNode temp = headA; while (temp != null) { visited.add(temp); temp = temp.next; } temp = headB; while (temp != null) { if (visited.contains(temp)) { return temp; } temp = temp.next; } return null; } //高效方法 public ListNode getIntersectionNode1(ListNode headA, ListNode headB) { ListNode A = headA, B = headB; while (A != B) { A = A != null ? A.next : headB; B = B != null ? B.next : headA; } return A; } }