当前位置 博文首页 > 中流击水,浪遏飞舟:双指针&&哈希&&剑指 Offer

    中流击水,浪遏飞舟:双指针&&哈希&&剑指 Offer

    作者:[db:作者] 时间:2021-08-26 12:44

    首先想到的是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;
        }
    };
    
    cs