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 trueChallenge
Follow up: Can you solve it without using extra space?LeetCode上的原题,请参见我之前的博客。
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; }};
本文转自博客园Grandyang的博客,原文链接:,如需转载请自行联系原博主。