方法一:暴力法+求长度法(不推荐)
函数代码:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p=headA;
int len1=0;
ListNode *q=headB;
int len2=0;
int dis=0;
while(p)
{
p=p->next;
len1++;
}
while(q)
{
q=q->next;
len2++;
}
p=headA;
q=headB;
if(len1>len2)
{
dis=len1-len2;
while(dis--)
{
p=p->next;
}
}
else
{
dis=len2-len1;
while(dis--)
{
q=q->next;
}
}
while(p!=q)
{
p=p->next;
q=q->next;
}
return p;
}
};
方法二推荐:循环遍历+头尾相接法
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p=headA;
ListNode *q=headB;
while(p!=q)
{
p=p==NULL?headB:p->next;
q=q==NULL?headA:q->next;
}
return p;
}
};