面试题37_两个链表的第一个公共结点

来源:互联网 发布:魏延被谁杀 知乎 编辑:程序博客网 时间:2024/05/20 02:29

题目描述


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


解题思路

1、首先遍历两个链表,获得各自长度,得到长度差k

2、让长的链表先走K 步

3、两个链表同时向后走,同时判断是否相等,若相等则返回。

时间复杂度:O(n),空间复杂度O(1)


实现代码

/*struct ListNode {int val;struct ListNode *next;ListNode(int x) :val(x), next(NULL) {}};*/class Solution {public:    ListNode* FindFirstCommonNode( ListNode *pHead1, ListNode *pHead2) {                if(pHead1 == nullptr || pHead2 == nullptr)            return nullptr;        int len1 = getLength(pHead1);        int len2 = getLength(pHead2);                int gap = len1-len2;        ListNode *pLongHead = pHead1;        ListNode *pShortHead = pHead2;                if(len2 > len1)        {        gap = len2-len1;        ListNode *pLongHead = pHead2;        ListNode *pShortHead = pHead1;            }                for(int i=0; i<gap;i++)            pLongHead = pLongHead->next;                while(pLongHead != nullptr && pShortHead != nullptr && pLongHead != pShortHead)        {        pLongHead = pLongHead->next;            pShortHead = pShortHead->next;        }                ListNode *ans = pLongHead;        return ans;            }        int getLength(ListNode *pHead)    {    if(pHead == nullptr)            return 0;        int ret = 0;                while(pHead != nullptr)        {       ret++;            pHead = pHead->next;        }                return ret;    }};


0 0