[leetCode]160.相交链表

在这里插入图片描述

暴力法

每次从一个链表中取出一个结点,将该结点与另一个链表所有结点比对如果相等则返回当前结点。

/**
 * 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) {
        ListNode pA = headA;
        ListNode pB = headB;
        while(pA!=null){
            while(pB!=null){
                if(pA == pB) return pA;
                pB = pB.next;
            }
            pA = pA.next;
            pB = headB;
        }
        return null;
    }
}

哈希表

将一个链表的元素加入哈希表,遍历另一个链表判断其结点是否存在于哈希表中。

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        HashSet<ListNode> set = new HashSet<>();
        while(headA!=null && !set.contains(headA)){
            set.add(headA);
            headA = headA.next;
        }
        while(headB != null){
            if(set.contains(headB)) return headB;
            headB = headB.next;
        }
        return null;
    }
}

双指针

public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        ListNode pA = headA;
        ListNode pB = headB;
        if(pA == null ||  pB == null) return null;
        while(pA !=null || pB != null){
            if(pA == null) pA = headB;
            else if(pB == null) pB = headA;
            if(pA == pB) return pB;
            pA = pA.next;
            pB = pB.next;
        }
        return null;
    }
}
public class Solution {
    public ListNode getIntersectionNode(ListNode headA, ListNode headB) {
        if(headA == null ||  headB == null) return null;
        ListNode pA = headA;
        ListNode pB = headB;
        while(pA != pB){
            pA = (pA == null ? headB : pA.next);
            pB = (pB == null ? headA : pB.next);
        }
        return pB;
    }
}
原文地址:https://www.cnblogs.com/PythonFCG/p/13859998.html