码迷,mamicode.com
首页 > 其他好文 > 详细

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

时间:2017-08-03 17:38:01      阅读:123      评论:0      收藏:0      [点我收藏+]

标签:common   log   offer   class   tle   turn   --   struct   null   

/*
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---两个链表的第一个公共结点

标签:common   log   offer   class   tle   turn   --   struct   null   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!