题目:

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        if(!headA||!headB)return NULL;
        int num1=0,num2=0,diff=0;
        ListNode* curA=headA;
        ListNode* curB=headB;
        while(curA){                    //计算链表长度差的时候要用cur,不可以直接用head,因为后面找相交节点的时候要从head开始找
            num1++;
            curA=curA->next;
        }
        while(curB){
            num2++;
            curB=curB->next;
        }
        diff=abs(num1-num2);
        if(num1>num2){
            while(diff){
                headA=headA->next;
                diff--;
            }
        }
        else if(num1<num2){              //让尾部对齐,即将长的链表的头指针移动到与短链表头指针对齐的位置
            while(diff){
                headB=headB->next;
                diff--;
            }
        }
        while(headA){
            if(headA==headB) return headA;
            else{
                headA=headA->next;
                headB=headB->next;
            }
        }
        return NULL;
    }
};
posted on 2023-07-25 21:15  孜孜不倦fly  阅读(15)  评论(0)    收藏  举报