[剑指offer]两个链表的第一个公共结点

在这里插入图片描述
思路:
把一个链表结点存到hashmap里,遍历另一个链表对hashmap对象使用containskey方法判断即可
实现:

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
import java.util.HashMap;
public class Solution {
    public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode cur1 = pHead1;
        ListNode cur2 = pHead2;
        
        HashMap<ListNode,Integer> map = new HashMap<>();
        while(cur1 != null){
            map.put(cur1,null);
            cur1 = cur1.next;
        }
        while(cur2 != null){
            if(map.containsKey(cur2)){
                return cur2;
            }
            cur2 = cur2.next;
        }
        return null;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_37344518/article/details/84941347