目录
1 题目描述
输入两个链表的头结点,若两个链表相交,返回交点结点,否则,返回null
2 解题思路
首先,我们不难想到:若两个链表相交,肯定成“倒Y”型。所以,我们可以将长度长一点的链表先走“差值”步,再次,两个链表同时走,若相交且没有走到尾结点处,返回该结点,否则,返回null
3 代码实现
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
//定义两个引用分别指向两个头结点
ListNode pl = pHead1;
ListNode ps = pHead2;
int lenA = 0;
int lenB = 0;
while(pl != null){
lenA++;
pl = pl.next;
}
while(ps != null){
lenB++;
ps = ps.next;
}
//将pl和ps重新指向各自的结点
pl = pHead1;
ps = pHead2;
//pl指向链表长度长的那个
int len = lenA - lenB;
if(len <= 0){
pl = pHead2;
ps = pHead1;
len = -len;
}
for(int i = 0;i < len;i++){
pl = pl.next;
}
while(pl != null&&ps != null&&pl != ps){
pl = pl.next;
ps = ps.next;
}
//判断当两个链表没有相交时,即两个链表尾结点为null,返回null
if(pl == ps&&pl == null){
return null;
}
return pl;
}