面试题02.07:
给你两个单链表的头节点 headA 和 headB ,请你找出并返回两个单链表相交的起始节点。如果两个链表没有交点,返回 null 。
方案一
public class Solution {public ListNode getIntersectionNode(ListNode headA, ListNode headB) {ListNode tempA = headA;ListNode tempB = headB;if (tempA == tempB){return tempA;}HashSet<ListNode> set = new HashSet<>();while (tempA != null || tempB != null) {if (tempA != null && tempB != null && tempA == tempB){return tempA;}if (tempA != null && set.contains(tempA)) {return tempA;}if (tempB != null && set.contains(tempB)) {return tempB;}set.add(tempA);set.add(tempB);if (tempA != null){tempA = tempA.next;}if (tempB != null){tempB = tempB.next;}}return null;}}
