题目要求:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
代码:
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head == NULL)
{
return false;
}
ListNode* slow_ptr = head, *fast_ptr = head;
while(fast_ptr->next != NULL)
{
fast_ptr = fast_ptr->next->next;
if(fast_ptr == NULL)
return false;
slow_ptr = slow_ptr->next;
if(fast_ptr == slow_ptr)
return true;
}
return false;
}
};