剑指offer---两个链表的第一个公共结点

题目:

输入两个链表,找出他们的第一个公共结点。

思路:

先计算出两个链表各自的长度,然后比较两个的长度,计算出长度差,一个指针指向长链表先走长度差,然后再定义一个指针,从头开始,一起走。当走到两个指针同时指向的结点,则找到他们的第一个公共结点。

class Solution {
public:
    size_t GetListLength(ListNode* pHead)
    {
        size_t len = 0;
        ListNode* pNode = pHead;
        while (pNode != NULL)
        {
            ++len;
            pNode = pNode->next;
        }
        return len;
    }

    ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) {
        //计算两个链表的长度
        size_t len1 = GetListLength(pHead1);
        size_t len2 = GetListLength(pHead2);

        ListNode* pListLong = pHead1;//假设以pHead1为头的链表长
        ListNode* pListShort = pHead2;
        int tmp = len1 - len2;

        //如果以pHead2为头的链表长
        if (len2 > len1)
        {
            pListLong = pHead2;
            pListShort = pHead1;
            tmp = len2 - len1;
        }

        //先在长链表上走tmp步,再同时走
        for (int i = 0; i < tmp; ++i)
        {
            pListLong = pListLong->next;
        }

        while (pListLong&&pListShort&&pListLong!=pListShort)
        {
            pListLong = pListLong->next;
            pListShort = pListShort->next;
        }

        return pListLong;
    }
};

猜你喜欢

转载自blog.csdn.net/zwe7616175/article/details/80991522