题解 | #两个链表的第一个公共结点#
两个链表的第一个公共结点
http://www.nowcoder.com/practice/6ab1d9a29e88450685099d45c9e31e46
这是2021年的第一题,主要是找到链表长度这个工具,再根据双链表Y的形状,配合快慢指针,找到突破口。tt
/* struct ListNode { int val; struct ListNode next; ListNode(int x) : val(x), next(NULL) { } };/ //null表示符号 class Solution { public: ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) { int L1 = GetLength(pHead1); int L2 = GetLength(pHead2);
//move bigger
int step=0;
ListNode *fast = NULL, *slow =NULL;
if(L2 >=L1)
{
step = L2 - L1;
fast=pHead2;
slow=pHead1;
}else{
step = L1 - L2;
fast=pHead1;
slow=pHead2;
}
//等长比较
while(step-- >0)
{
fast=fast->next;
}
while(fast!=slow && fast!=NULL && slow!=NULL ){
fast=fast->next;
slow=slow->next;
}
if(fast==NULL){
return fast;}
else{
return fast;
}
}
int GetLength(ListNode* pH)
{
if(pH==NULL )return 0;
int len=0;
while(pH!=NULL){
len++;
pH=pH->next;
}
return len;
}
};