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

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

//用一个set,如果插入某一个指针,set的数值无变化,则该结点就是公共结点
class Solution {
public:
    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        set<ListNode*> the_set;
        ListNode* p1=pHead1,*p2=pHead2;
        while(p1!=NULL||p2!=NULL)
        {
            int pre_size=the_set.size();
            if(p1!=NULL)
            {
                the_set.insert(p1);
                if(the_set.size()==pre_size)return p1;
                pre_size++;
                p1=p1->next;
            }
            if(p2!=NULL)
            {
                the_set.insert(p2);
                if(the_set.size()==pre_size)return p2;
                pre_size++;
                p2=p2->next;
            }
        }
        return NULL;;
    }
};

猜你喜欢

转载自blog.csdn.net/xiaocongcxc/article/details/82766028