想法:遍历两个链表到最后,判断连个链表最后的位置是否相同,不同直接返回;用两个变量记录链表的长度,哪个长 先往后遍历到一样长,接着另一个也开始同时遍历,直到相等,返回头指针
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB)
{
// write your code here
if(headA==NULL||headB==NULL)
return NULL;
ListNode *p = headA;
ListNode *q = headB;
int a=1,b=1;
while(p->next!=NULL)
{
p=p->next;
a+=1;
}
while(q->next!=NULL)
{
q=q->next;
b+=1;
}
if(q!=p)
return NULL;
if(a>b)
{
for(int i=0;i<a-b;i++)
{
headA=headA->next;
}
}
else if(a<b)
{
for(int j=0;j<b-a;j++)
{
headB=headB->next;
}
}
while(headA!=headB)
{
headA=headA->next;
headB=headB->next;
}
return headA;
}