题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
import java.util.*; import java.util.HashMap; /* public class ListNode { int val; ListNode next = null; ListNode(int val) { this.val = val; } }*/ public class Solution { public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { HashMap<ListNode,Integer> ans = new HashMap<>(); ListNode temp1 = pHead1; while(temp1 != null){ // 先把链表 1 遍历一遍,用哈希保存 ans.put(temp1,temp1.val); temp1 = temp1.next; } ListNode temp2 = pHead2; while(temp2 != null){ if(ans.containsKey(temp2)){ // 遍历链表 2 的时候,比较链表 2 的节点是否在哈希中出现,出现则返回当前节点 return temp2; } temp2 = temp2.next; } return null; // 如果跑出循环,说明没有相同节点,则返回 null } }