其他分享
首页 > 其他分享> > 剑指 Offer 52. 两个链表的第一个公共节点

剑指 Offer 52. 两个链表的第一个公共节点

作者:互联网

题意

如题目所示

思路

代码

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode* cur1 = headA;
        ListNode* cur2 = headB;
        int len1 = 0, len2 = 0;
        while(cur1) {
            len1++;
            cur1 = cur1->next;
        }
        while(cur2) {
            len2++;
            cur2 = cur2->next;
        }
        int dis = abs(len1 - len2);     //统计长度差,
        ListNode *longer, *shorter;
        if(len1 > len2) {
            longer = headA;
            shorter = headB;
        }else {
            longer = headB;
            shorter = headA;
        }       //选出较长的链表,设置指针
        while(dis--) {
            longer = longer->next;
        }       //较长链表的指针先走「距离差的步数」
        while(longer != shorter) {
            longer = longer->next;
            shorter = shorter->next;
        }       //直到周到公共结点orNUll为止
        return longer;
    }
};

标签:shorter,结点,ListNode,longer,Offer,52,链表,指针
来源: https://www.cnblogs.com/MartinLwx/p/14396019.html