题目:输入两个链表,找出它们的第一个公共结点。
思路:
代码:
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if (pHead1 == null || pHead2 == null) {
return null;
}
ListNode node1 = pHead1;
ListNode node2 = pHead2;
while (node1 != node2) {
// 长度相同有公共结点,第一次就遍历到;没有公共结点,走到尾部NULL相遇,返回NULL
// 长度不同有公共结点,第一遍差值就出来了,第二遍一起到公共结点;没有公共,一起到结尾NULL。
node1 = (node1 == null ? pHead2 : node1.next);
node2 = (node2 == null ? pHead1 : node2.next);
}
return node1;
}