# My AC C++ Solution of intersection of Two Linked Lists with O(m+n) time and O(1) space

• ``````ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
return NULL;

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;
}
else
{
lastA=pre;
}
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
{
while(fast!=slow)
{
fast=fast->next;
slow=slow->next;
}

lastA->next=NULL;//recover A's tail
return fast;
}

}``````

• This post is deleted!

• I use the same method as yours and also set lastA->next=NULL. But it still complains that the linked structure is modified. I don't know why

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.