剑指offer35

164 阅读1分钟

题目描述

输入两个链表,找出它们的第一个公共结点。

解题思路分析

如果两个链表有公共节点的话,其实形状就会有点像Y了,如下图所示

链表
然后这里我们可以使用HashMap来存储遍历的第一个链表,然后再遍历第二个链表,碰到相同的就可以直接返回了

public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
        ListNode current1 = pHead1;
        ListNode current2 = pHead2;
        
        HashMap<ListNode, Integer> hashMap = new HashMap<ListNode, Integer>();
        while (current1 != null) {
            hashMap.put(current1, null);
            current1 = current1.next;
        }
        while (current2 != null) {
            if (hashMap.containsKey(current2))
                return current2;
            current2 = current2.next;
        }
        return null;
    }