2026/02/20

[LeetCode] 141 : Linked List Cycle

Naive version
  1. /**
  2. * Definition for singly-linked list.
  3. * struct ListNode {
  4. * int val;
  5. * ListNode *next;
  6. * ListNode(int x) : val(x), next(NULL) {}
  7. * };
  8. */
  9. class Solution {
  10. public:
  11. bool hasCycle(ListNode *head) {
  12. std::map<ListNode*, bool> nodeMap;
  13. ListNode* curNode = head;
  14. nodeMap[curNode] = true;
  15. while(curNode != nullptr) {
  16. curNode = curNode->next;
  17. if (nodeMap[curNode])
  18. return true;
  19. else
  20. nodeMap[curNode] = true;
  21. }
  22. return false;
  23. }
  24. };
Follow up : two pointer version for O(1) memory
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
  ListNode* takeOneStep(ListNode *node) {
    if (node == nullptr)
      return nullptr;
    return node->next;
  }

  ListNode* takeTwoStep(ListNode *node) {
    if (node == nullptr)
      return nullptr;
    ListNode* tmp = node->next;
    if (tmp == nullptr)
      return nullptr;
    return tmp->next;
  }

  bool hasCycle(ListNode *head) {
    ListNode* stepOneNode = takeOneStep(head);
    ListNode* stepTwoNode = takeTwoStep(head);
    
    while (stepOneNode != nullptr && stepTwoNode != nullptr) {
      if (stepOneNode == stepTwoNode)
        return true;
      stepOneNode = takeOneStep(stepOneNode);
      stepTwoNode = takeTwoStep(stepTwoNode);
    }

    return false;
  }
};