leetcode

141.环形链表

力扣链接

快慢指针

class Solution {
public:
    bool hasCycle(ListNode *head) {
      ListNode *slow = head, *fast = head;
      while (fast && fast->next) {
        slow = slow->next;
        fast = fast->next->next;
        if (slow == fast) return true;
      }
      return false;
    }
};

哈希表

class Solution {
public:
    bool hasCycle(ListNode *head) {
        std::unordered_set<ListNode*> uset;
        ListNode* current = head;
        while(current){
            if (uset.find(current)!=uset.end()) return true;
            uset.insert(current);
            current = current->next;
        }
        return false;
    }
};