题目描述
输入两个链表,找出它们的第一个公共结点。
使用HashSet存储结点即可。
package com.niuke;
import java.util.HashSet;
/**
*
* @author 周颖
* @date 2017年10月6日 上午9:33:59
* @Decription 输入两个链表,找出它们的第一个公共结点。
*/
public class Ex24 {
class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
HashSet<ListNode> set = new HashSet<>();
ListNode current1 = pHead1;
ListNode current2 = pHead2;
while(current1!=null){
set.add(current1);
current1 = current1.next;
}
while(current2!=null){
if (set.contains(current2)) {
return current2;
}
current2 = current2.next;
}
return null;
}
}