双指针&&哈希&&剑指 Offer 52. 两个链表的第一个公共节点

首先想到的是vector< int >存储节点值然后比较,或者弄两次前插从尾部读取公共部分,但是太麻烦了,而且比较的貌似是内存地址,不是值,如下图这组数据:
公共部分
参考了力扣官方题解:
两个链表的第一个公共节点

1.双指针

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        ListNode*curA=headA;
        ListNode*curB=headB;
        while(curA!=curB){
            curA=curA==NULL?headA:curA->next;
            curB=curB==NULL?headB:curB->next;
        }
        return curA;
    }
};

2.哈希

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        unordered_set<ListNode*> tmp;
        ListNode* curA=headA;
        ListNode* curB=headB;
        while(curA){
            tmp.insert(curA);
            curA=curA->next;
        }
        while(curB){
            if(tmp.count(curB)){	//if(tmp.find(curB)!=tmp.end()
                return curB;
            }
            curB=curB->next;
        }
        return NULL;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值