Leetcode刷题笔记(c++)_热题 HOT 100_160. 相交链表

双指针

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        unordered_set<ListNode*>hashset;
        ListNode *hA=headA,*hB=headB;
        while(hB!=hA){
            hA=hA==NULL?headB:hA->next;
            hB=hB==NULL?headA:hB->next;
        }
        return hA;        
    }
};

哈希表

class Solution {
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
        unordered_set<ListNode*>hashset;
        while(headA){
            hashset.insert(headA);
            headA=headA->next;
        }
        while(headB){
            if(hashset.count(headB))return headB;
            headB=headB->next;
        }
        return NULL;        
    }
};

你可能感兴趣的:(链表,leetcode,c++)