题目描述
输入两个链表,找出它们的第一个公共结点。
代码
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {
// 得到两个链表的长度
unsigned int nLength1 = GetListLength(pHead1);
unsigned int nLength2 = GetListLength(pHead2);
int nLengthDif = nLength1 - nLength2;
ListNode *pListHeadLong = pHead1;
ListNode *pListHeadshort = pHead2;
if (nLength2 > nLength1)
{
pListHeadLong = pHead2;
pListHeadshort = pHead1;
nLengthDif = nLength2 - nLength1;
}
// 先在长链表上走几步,再同时在两个链表上遍历
for (int i = 0; i < nLengthDif; ++i)
{
pListHeadLong = pListHeadLong->next;
}
while((pListHeadLong != NULL) && (pListHeadshort != NULL) && (pListHeadLong != pListHeadshort)) {
pListHeadshort = pListHeadshort->next;
pListHeadLong = pListHeadLong->next;
}
// 得到第一个公共节点
ListNode *pFirstCommonNode = pListHeadLong;
return pFirstCommonNode;
}
// 获取链表的长度
unsigned int GetListLength(ListNode *pHead)
{
unsigned int nLength = 0;
ListNode *pNode = pHead;
while(pNode != NULL) {
nLength ++;
pNode = pNode->next;
}
return nLength;
}
};