about this problem,
1.calculate the precise length of the two linked list.
2.calculate the difference value of two length of the linked list.
then move the head node difference value of steps behind head. then, we can just use a while clause to find the intersection of two linked list.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
ListNode *p;
ListNode *q;
p = headA;
q = headB;
int lengtha = 0;
int lengthb = 0;
while(p!= NULL)
{
p = p->next;
lengtha++;
}
while(q!= NULL)
{
q = q->next;
lengthb++;
}
if(lengtha >lengthb)
{
int cha = lengtha - lengthb;
p = headA;
q = headB;
while(cha!=0)
{
p = p->next;
cha--;
}
}
else
{
int cha = lengthb - lengtha;
p = headA;
q = headB;
while(cha!= 0)
{
q = q->next;
cha --;
}
}
while(p!=q && p!= NULL && q!= NULL)
{
p = p->next;
q = q->next;
}
return p;
}
};