力扣-141题 环形链表(C++)- unordered_set中存放链表节点及其相关注意点

题目链接:https://leetcode-cn.com/problems/linked-list-cycle/
题目如下:
在这里插入图片描述
在这里插入图片描述

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    bool hasCycle(ListNode *head) {
        //tip:  unordered_set
        //a.find("1234")   set中不可为空,若找不到,则返回a.end();
        //a.count("1234")  set中可以为空,其中元素不可重复,故返回值为0或1
        unordered_set<ListNode*> hash_set;

        while(head){
            if(hash_set.count(head)) return true;
            else hash_set.insert(head);
            head=head->next;
        }
        return false;
    }
};

版权声明:本文为qq_40467670原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。