查找二个链表的第一个交叉节点:
首先查询二条链表的各自长度,其次长链表上先移动长度差的步数,然后同时遍历二个链表即可:
/**
* 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 *A=headA;
ListNode *B=headB;
int len1=0,len2=0;
while(headA!=NULL)
{
len1++;
headA = headA->next;
}
while(headB!=NULL)
{
len2++;
headB=headB->next;
}
if(len1>len2)
{
int len=len1-len2;
while(len>0)
{
len--;
A=A->next;
}
}
if(len1<len2)
{
int len=len2-len1;
while(len>0)
{
len--;
B=B->next;
}
}
while(A!=NULL&&B!=NULL)
{
if(A==B)
return A;
else
{
A=A->next;
B=B->next;
}
}
return NULL;
}
};