输入两个无环的单向链表,找出它们的第一个公共结点,如果没有公共节点则返回空。(注意因为传入数据是链表,所以错误测试数据的提示是用其他方式显示的,保证传入数据是正确的)
数据范围: n le 1000n≤1000
要求:空间复杂度 O(1),时间复杂度 O(n)
将两个链表变成a+b,b+a的形式,此时两个链表的长度相同。再一一进行比较
题解(java)public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1 = pHead1;
ListNode p2 = pHead2;
if(pHead1 == null || pHead2 == null)
return null;
while(p1 != p2){
p1 = p1.next;
p2 = p2.next;
//让两个链表的长度相等
if(p1 != p2){
if (p1 == null) p1 = pHead2;
if (p2 == null) p2 = pHead1;
}
}
return p1;
}
}



