题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) { //参数校验 if(pHead1 == null || pHead2 == null) return null; if(pHead1.next == null) return pHead1; if(pHead2.next == null) return pHead2; //将其中一个链表的数据存储结合中 List<ListNode> intList = new ArrayList<>(); while(pHead1 != null){ intList.add(pHead1); pHead1 = pHead1.next; } //在另一个集合中找到对应的元素 while(pHead2 != null){ if(intList.contains(pHead2)){ return pHead2; } pHead2 = pHead2.next; } return null; }
解题思路:
1、很传统的一种解法,用一个集合存储其中链表中的每一个节点
2、遍历另一个链表的每一个节点,使用集合中的contains方法,可判断列表中是否有与当前遍历链表中相同的节点.