Given a linked list, determine if it has a cycle in it.

Example
Given -21->10->4->5, tail connects to node index 1, return true

Challenge
Follow up:
Can you solve it without using extra space?

 

LeetCode上的原题,请参见我之前的博客Linked List Cycle

 

class Solution {
public:
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    bool hasCycle(ListNode *head) {
        if (!head) return false;
        ListNode *slow = head, *fast = head;
        while (fast && fast->next) {
            slow = slow->next;
            fast = fast->next->next;
            if (slow == fast) return true;
        }
        return false;
    }
};

 

相关文章:

  • 2021-12-30
  • 2021-05-19
  • 2021-06-18
  • 2022-12-23
  • 2022-12-23
  • 2021-11-20
  • 2021-10-01
  • 2021-10-22
猜你喜欢
  • 2022-12-23
  • 2021-09-11
  • 2022-01-10
  • 2022-01-16
  • 2021-07-19
  • 2022-12-23
  • 2021-07-14
相关资源
相似解决方案