- Intersection of Two Linked Lists
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.
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(NULL == headA || NULL == headB) //如果两个链表有一个为空则返回空,不存在相交的点
{
return NULL;
}
ListNode *p1 = headA;
ListNode *p2 = headB;
ListNode * result=NULL; //用来保存结果的节点
int len1 = 0;
int len2 = 0;
while(p1) //遍历获得链表1的长度
{
len1++;
p1 = p1->next;
}
while(p2)//遍历获得链表2的长度
{
len2++;
p2 = p2->next;
}
if(len2 > len1)//使得p1始终指向长的链表,p2指向短的链表
{
p1 = headB;
p2 = headA;
}
else
{
p1 = headA;
p2 = headB;
}
int len = abs(len1 - len2);
while(len) //长的链表先走完长的节点
{
p1 = p1->next;
len--;
}
while(p1&&p2)
{
if(p1->val == p2->val) //如果相等则找到相交的节点
{
result = p1;
break;
}
else
{
p1 = p1->next;
p2 = p2->next;
}
}
return result;
}
//最开始提交的代码错误的原因,我去~~~~~~~
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if(NULL == headA || NULL == headB)
{
return NULL;
}
ListNode *p1 = headA;
ListNode *p2 = headB;
int len1 = 0;
int len2 = 0;
while(p1)
{
len1++;
p1 = p1->next;
}
while(p2)
{
len2++;
p2 = p2->next;
}
p1 = headA; //注意这两句不能少,开始就是因为缺少这两句,我去~~~~~~~~~~~
p2 = headB;
int num = abs(len1 - len2);
while(num)
{
if(len1 >len2)
{
p1 = p1->next;
//cout<<" 1 p1->val="<<p1->val<<" ";
}
else
{
p2 = p2->next;
}
num--;
}
while(p1 && p2)
{
if(p1->val== p2->val)
{
return p1;
break;
}
p1 = p1->next;
p2 = p2->next;
}
return NULL;
}