两个链表的第一个公共结点

2017-03-24  本文已影响0人  安然_fc00
    ListNode* FindFirstCommonNode( ListNode* head1, ListNode* head2) {
        int Length1 = GetLength(head1);
        int Length2 = GetLength(head2);
        int LengthDif = Length1 - Length2;
        ListNode* pLongListHead = head1;
        ListNode* pShortListHead = head2;
         
        if (Length1 < Length2)
        {
            LengthDif = Length2 -Length1;
            pLongListHead = head2;
            pShortListHead = head1;
        }
         
        for(int i = 0; i<LengthDif ;i++)
        {
            pLongListHead = pLongListHead->next;
        }
         
        while(pLongListHead != NULL && pShortListHead != NULL && pLongListHead != pShortListHead)
        {
            pLongListHead = pLongListHead->next;
            pShortListHead = pShortListHead->next;
        }
         
        return pLongListHead;
    }
     
    int GetLength(ListNode* head){//获取链表的长度
        int length = 0;
        while(head != NULL)
        {
            length++;
            head = head->next;
        }
        return length;
    }
上一篇 下一篇

猜你喜欢

热点阅读