[Leetcode]环形链表 II

题目

 

代码 

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    ListNode *detectCycle(ListNode *head) {
        set<long> address;
        auto ptr=head;
        long realAdd;
        while(true)
        {
            if(ptr==nullptr)
                return nullptr;
            if(address.find(reinterpret_cast<long>(ptr))!=address.end())
            {
                realAdd=reinterpret_cast<long>(ptr);
                break;
            }else
            {
                address.insert(reinterpret_cast<long>(ptr));
            }
            ptr=ptr->next;
        }
        ptr=head;
        while(head!=nullptr)
        {
            if(reinterpret_cast<long>(head)==realAdd)
                return head;
            head=head->next;
        }
        return nullptr;
        
    }
};

 思路

用set保存链表中每个结点的地址,第一次遍历将所有地址保存进入set,当地址发生重复的时候,在set中就能查找到。

原文地址:https://www.cnblogs.com/lizhenghao126/p/11053565.html