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; } };
本文转自博客园Grandyang的博客,原文链接:单链表中的环[LintCode] Linked List Cycle ,如需转载请自行联系原博主。