rocksc30 / LeetCode

用于力扣刷题打卡
2 stars 0 forks source link

160. 相交链表 #14

Open rocksc30 opened 1 year ago

rocksc30 commented 1 year ago

Java --> 哈希表解法

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        Set<ListNode> aSet = new HashSet<>();
        ListNode pA = headA, pB = headB;
        while(pA != null){
            aSet.add(pA);
            pA = pA.next;
        }

        while(pB != null){
            if(aSet.contains(pB)){
                return pB;
            }
            pB = pB.next;
        }
        return null;
    }
}