题目 :找到2个链表的交叉点
分析:对2链表而言,若交叉,则必定末尾一个结点相同。故可以此判断交叉点的存在。而对于找到交叉点的 具体位置,若一一比较,需要O(m*n)的复杂度。考虑到交叉链表尾端相同,仅前端不同,可以让长链表先走它多余的长度,随后2链表一起走,即可保证同时到达交点。
答案:
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
if (headA == NULL || headB == NULL)
return NULL;
// length of a
ListNode *curra = headA;
int lenA = 1;
while ( curra->next)
{
lenA ++;
curra = curra->next;
}
// length of b
ListNode *currb = headB;
int lenB = 1;
while ( currb->next)
{
lenB ++;
currb = currb->next;
}
// if intersected
if (curra != currb)
return NULL;
ListNode *ha = headA;
ListNode *hb = headB;
// cancle the distance
int dis = lenA - lenB;
if (dis > 0) //A go dis
{
while(dis)
{
ha = ha->next;
dis --;
}
}
else // b go
{
dis = - dis;
while(dis)
{
hb = hb->next;
dis --;
}
}
// go to the intersection
while (ha)
{
if (ha == hb)
return ha;
else
{
ha = ha->next;
hb = hb->next;
}
}
}
};