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 = head;
ListNode *fast = head->next;
while (fast != NULL && fast->next != NULL) {
if (slow == fast) // 有环则一定在head前一个节点相遇,故花费(n-1)的时间
return true;
slow = slow->next;
fast = fast->next->next;
}
return false;
}
};