LeetCode:相交链表

158 阅读1分钟

每日一题有来啦,秋招冲!!!

一、相交链表

image.png

二、哈希法、双指针法、差值法

package cn.edu.neu.leetcode;

import java.util.HashSet;
import java.util.Set;

/**
 * @author 32098
 */
public class IntersectLinkedList {
    /**
     * 哈希集合法
     * @param headA headA
     * @param headB headB
     * @return ListNode
     */
    public static ListNode getIntersectionNode1(ListNode headA, ListNode headB) {
        Set<ListNode> 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;
    }

    /**
     * 双指针法
     * @param headA headA
     * @param headB headB
     * @return ListNode
     */
    public static ListNode getIntersectionNode2(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 pa;
    }

    /**
     * 差值法
     * @param headA headA
     * @param headB headB
     * @return ListNode
     */
    public static ListNode getIntersectionNode3(ListNode headA, ListNode headB) {
        if (headA == null || headB == null){
            return null;
        }
        int lenA = 0, lenB = 0;
        ListNode tmp = headA;
        while (tmp!=null){
            tmp = tmp.next;
            lenA ++;
        }
        tmp = headB;
        while (tmp!=null){
            tmp = tmp.next;
            lenB++;
        }
        int minus = lenA-lenB;
        while (minus!=0){
            if(minus<0){
                headB = headB.next;
                minus++;
            }else {
                headA = headA.next;
                minus--;
            }
        }
        while (headA!=null && headB!=null){
            if(headA.equals(headB)){
                return headA;
            }else {
                headA = headA.next;
                headB = headB.next;
            }
        }
        return null;
    }

    public static void main(String[] args) {

    }
}
双指针与差值法挺好。