这题的难点在于理解单链表中如果有第一个公共节点,那么其后的所有节点都重合。
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
if(pHead1 == null || pHead2 == null){
return null;
}
//记录它们的长度可以不用两个辅助栈,让长的先走,可以同时到链尾
int nLen1 = GetListLength(pHead1);
int nLen2 = GetListLength(pHead2);
int nLenDif = nLen1 - nLen2;
//不妨假定pHead1较长
ListNode pListHeadLong = pHead1;
ListNode pListHeadShort = pHead2;
if(nLen2 > nLen2){
pListHeadLong = pHead2;
pListHeadShort = pHead1;
nLenDif = nLen2 - nLen1;
}
//先在长链表上走几步,再同时在两个链表上遍历
for(int i = 0; i < nLenDif; i ++){
pListHeadLong = pListHeadLong.next;
}
while((pListHeadLong != null) && (pListHeadShort != null)
&& (pListHeadLong != pListHeadShort)){
pListHeadLong = pListHeadLong.next;
pListHeadShort = pListHeadShort.next;
}
//得到第一个公共结点
return pListHeadLong;
}
private int GetListLength(ListNode pHead) {
int nLen = 0;
ListNode pNode = pHead;
while(pNode != null){
++ nLen;
pNode = pNode.next;
}
return nLen;
}
}