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

/*
struct ListNode {
    int val;
    struct ListNode *next;
    ListNode(int x) :
            val(x), next(NULL) {
    }
};*/
class Solution 
{
public:
    int Getlength(ListNode* pNode)
    {
        int length = 0;
        ListNode* A = pNode;
        while (A != NULL)
        {
            ++length;
            A = A->next;
        }
        return length;
    }
    ListNode* FindFirstCommonNode(ListNode* pHead1, ListNode* pHead2) 
    {
        int length1 = Getlength( pHead1);
        int length2 = Getlength( pHead2);
        int bushu = abs(length1 - length2);
        ListNode* curNode;
        ListNode* firstCommonNode;

        if (length1 >= length2)
        {
            curNode = pHead1;
            while (bushu != 0)
            {
                curNode = curNode->next;
                --bushu;
            }


            while ((pHead2 != NULL) && (curNode != NULL) && (curNode != pHead2))
            {
                pHead2 = pHead2->next;
                curNode = curNode->next;
            }

            firstCommonNode = curNode;
            return firstCommonNode;


        }
        else
        {
            curNode = pHead2;
            while (bushu != 0)
            {
                curNode = curNode->next;
                --bushu;
            }

            while ((pHead1 != NULL) && (curNode != NULL) && (curNode != pHead1))
            {
                pHead1 = pHead1->next;
                curNode = curNode->next;
            }

            firstCommonNode = curNode;
            return firstCommonNode;
        }



    }
};

 

posted @ 2017-08-03 17:17  双马尾是老公的方向盘  阅读(104)  评论(0编辑  收藏  举报