Leetcode学习笔记(160. 相交链表)

Leetcode学习笔记(160. 相交链表)_第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) {
        if(headA==nullptr||headB==nullptr)
            return nullptr;
        ListNode *curA=headA,*curB=headB;
        while(curA!=nullptr){
            while(curB!=nullptr){
                if(curB==curA)
                    return curA;
                curB = curB->next;
            }
            curA=curA->next;
            curB = headB;
        }
        return nullptr;
    }
};

Hash表:

/**
 * 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) {
        if(headA==nullptr||headB==nullptr)
            return nullptr;
        ListNode *curA=headA,*curB=headB;
        unordered_set<ListNode*> data;
        while(curA!=nullptr){
            data.insert(curA);
            curA=curA->next;
        }
        while(curB!=nullptr){
            if(data.find(curB)!=data.end())
                return curB;
            curB = curB->next;
        }
        return nullptr;
    }
};

双指针:

/**
 * 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) {
        if(headA==nullptr||headB==nullptr)
            return nullptr;
        ListNode *curA=headA,*curB=headB;
        bool signA=true,signB=true;
        while(curA!=nullptr||curB!=nullptr){
            if(curA==curB&&curA!=nullptr)
                return curA;
            curA = curA->next;
            curB = curB->next;
            if(curA==nullptr&&signA){
                curA=headB;
                signA=false;
            }
            if(curB==nullptr&&signB){
                curB=headA;
                signB=false;
            }
        }
        return nullptr;
    }
};

你可能感兴趣的:(LeetCode学习笔记,链表,leetcode,c++)