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

1.用map查找暴搜,时间复杂度O(mlogn),空间复杂度O(n);

    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        map<ListNode*,int> match;
        ListNode* head=pHead1;
        while(head)
        {
            match[head]=1;
            head=head->next;
        }
        head=pHead2;
        while(head)
        {
            if(match.find(head)!=match.end()) return head;
            head=head->next;
        }
       return NULL;
    }

2.利用栈,倒过来从公共节点开始搜索,直到遇到不公共的节点位置,时间复杂度O(m+n)空间复杂度O(m+n)

    ListNode* FindFirstCommonNode( ListNode* pHead1, ListNode* pHead2) {
        stack<ListNode*> shead1;
        stack<ListNode*> shead2;
        ListNode* commn=NULL;
        while(pHead1) 
        {
            shead1.push(pHead1);
            pHead1=pHead1->next;
        }
        while(pHead2) 
        {
            shead2.push(pHead2);
            pHead2=pHead2->next;
        }
        if(shead1.size()==0 || shead2.size()==0) return NULL;
        while (shead1.top()==shead2.top())
        {
            commn=shead1.top();
            shead1.pop();
            shead2.pop();
            if(shead1.size()==0 || shead2.size()==0) break;
        }
       return commn;
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值