题目描述
输入两个链表,找出它们的第一个公共结点。
分析:首先计算两个链表的长度,然后求长度差diff,随后将长链表向后移动diff位,最后同时移动求交点(两个链表相交,尾指针必然相同 参考https://blog.csdn.net/weixin_43871369/article/details/89242850)
参考代码:
/*
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};*/
class Solution {
public:
ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
if(pHead1==nullptr||pHead2==nullptr)
return nullptr;
int pcnt1=getLengthOfList(pHead1);
int pcnt2=getLengthOfList(pHead2);
ListNode *newpHead1,*newpHead2;
if(pcnt1>=pcnt2)
{
int diff=pcnt1-pcnt2;
newpHead1=WalkList(pHead1,diff);
newpHead2=pHead2;
}
else{
int d