返回第一个相交节点的指针,一般做法是用两个指针同时去遍历,但有个问题是两个链表在相交节点之前的节点数目不一致,这样两个指针就不能站在同一起跑线上遍历链表。所有得先求出两个链表的长度,让指向节点数目多的链表的指针先遍历,然后两个指针同时遍历,如果两个指针相同则返回这个指针。
class Solution {
public:
ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
int lenA=0;
int lenB=0;
int gap;
ListNode*pA=headA;
ListNode*pB=headB;
if(headB==NULL||headA==NULL){
return NULL;
}
while(pA!=NULL){//求链表的长度
lenA++;
pA=pA->next;
}
while(pB!=NULL){//求链表B的长度
lenB++;
pB=pB->next;
}
ListNode*curA=headA;
ListNode*curB=headB;
// 让curA为最长链表的头,lenA为其长度
if(lenB>lenA){
swap(lenA,lenB);
swap(curA,curB);
}
gap=lenA-lenB;
while(gap--){
curA=curA->next;// 让curA和curB在同一起点上(末尾位置对齐
}
// 遍历curA 和 curB,遇到相同则直接返回
while(curA!=NULL){
if(curA==curB){
return curA;
}
curA=curA->next;
curB=curB->next;
}
return NULL;
}
};