36、两个链表的第一个公共节点

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

class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        if(pHead1==NULL||pHead2==NULL)
             return NULL;
        int m = getLength(pHead1),n = getLength(pHead2);
        ListNode *p1 = pHead1;
        ListNode *p2 = pHead2;
        if(m>n)
        {
            int k = m - n;
            while(k>0)
            {
                p1 = p1->next;
                k--;
            }
            while(p1!=p2&&p1&&p2)
            {
                p1 = p1->next;
                p2 = p2->next;
            }
           return p1;
        }
        else
        {
            int k = n - m;
            while(k>0)
            {
                p2 = p2->next;
                k--;
            }
            while(p1!=p2&&p1&&p2)
            {
                p1 = p1->next;
                p2 = p2->next;
            }
           return p1;
        }
    }
    int getLength(ListNode* list)
    {
        int count = 0;
        while(list!=NULL)
        {
            list = list->next;
            count ++;
        }
        return count;
    }
};
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容