```
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(headA==NULL || headB==NULL)
return NULL;
ListNode *slow=headA;
ListNode *fast=headA;
ListNode *pre;
ListNode *lastA;//record A's tail
while(fast != NULL && fast->next != NULL)
{
slow=slow->next;
pre=fast->next;
fast=pre->next;
}
//connect B to A's tail and determine whether there is a loop and find the intersection
if(fast != NULL)
{
lastA=fast;
lastA->next=headB;
}
else
{
lastA=pre;
lastA->next=headB;
fast=headB;
}
while(fast != NULL && fast->next != NULL)
{
slow=slow->next;
fast=fast->next->next;
if(slow==fast)//if fast can reach slow, there is a intersection
break;
}
//no intersection
if(fast==NULL || fast->next==NULL)
{
lastA->next=NULL;//recover A's tail
return NULL;
}
else
{
fast=headA;//set fast to the headA and move one step every time
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}
lastA->next=NULL;//recover A's tail
return fast;
}
}
```