首页 > 其他 > 详细

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

时间:2017-08-03 17:22:19      阅读:180      评论:0      收藏:0      [点我收藏+]
/*
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;
        }



    }
};

 

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

原文:http://www.cnblogs.com/159269lzm/p/7280810.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!