题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
https://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
判断两个链表大小,把小链表数据添加到set里,遍历大链表直到出现set里的数据并返回
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
import java.util.*;
public class Solution {
int ListLen(ListNode head) {
int len = 0;
while (head != null) {
len++;
head = head.next;
}
return len;
}
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
int length1 = ListLen(pHead1), length2 = ListLen(pHead2);
ListNode res, res2;
if (length1 < length2) {
res = pHead1;
res2 = pHead2;
} else{
res2 = pHead1;
res = pHead2;
}
HashSet<ListNode> hSet = new HashSet<>();
while (res != null) {
hSet.add(res);
res = res.next;
}
while (res2 != null){
if(hSet.contains(res2))
return res2;
res2 = res2.next;
}
return null;
}
}
查看9道真题和解析