LeetCode系列160—相交链表

题意

相交链表

题解

方法一:哈希集合

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

方法二:双指针

class Solution {
    
    
public:
    ListNode *getIntersectionNode(ListNode *headA, ListNode *headB) {
    
    
        if (headA == nullptr || headB == nullptr) {
    
    
            return nullptr;
        }
        ListNode *pA = headA, *pB = headB;
        while (pA != pB) {
    
    
            pA = pA == nullptr ? headB : pA->next;
            pB = pB == nullptr ? headA : pB->next;
        }
        return pA;
    }
};

参考

相交链表

猜你喜欢

转载自blog.csdn.net/younothings/article/details/120213542