Write a program to find the node at which the intersection of two singly linked lists begins.
For example, the following two linked lists:
A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
begin to intersect at node c1.
Notes:
null.A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
长链为B ,所以B先走abs(6-5)=1步 长链的当前位置为 b2 ,然后 A从头 a1 两指针 一起往后走A: a1 → a2
↘
c1 → c2 → c3
↗
B: b1 → b2 → b3
此时 B的当前位置为 c3 然后指向A的指针指向b1(没有走完的头部) 当前位置和指向A的指针 同时往后走 ,当前位置指向NULL结束 ,指向A的指针此时指向b2 ,也就是上面求的 先走长度差步的位置,然后再按照剩下的走完,找到交点<span style="font-size:18px;">/**
* 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) {
if(headA==NULL||headB==NULL)
return NULL;
ListNode *p,*q;
p=headA;
q=headB;
int numA=0; //定义numA用来记录headA的链结点个数
int numB=0;//定义numB用来记录headB的链结点个数
while(p)
{
++numA;
p=p->next;
}
while(q)
{
++numB;
q=q->next;
}
p=headA;
q=headB;
int temp=abs(numA-numB);
if(numA>numB) //判断哪个链长,长的那根链先走 |numA-numB| 步
{
while(temp>0)
{
p=p->next;
--temp;
}
}
else
{
while(temp>0)
{
q=q->next;
--temp;
}
}
while(p&&q) //长的走完之后 , 两者一起走 直到遇到重叠的节点
{
if(p==q)
return p;
p=p->next;
q=q->next;
}
return NULL;
}
};</span>Intersection of Two Linked Lists leetcode
原文:http://blog.csdn.net/yujin753/article/details/42245057