Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
判断一个链表是否有环。条件是能否用O(1)的空间复杂度解决这个问题。既然不让我们用多余的空间,那么我们首先想到的是遍历这个链表,我们维持两个指针,一个快,一个慢,如果有环的话,慢点必然和快的相遇;没有环的话,快的首先指向空指针,问题结束。下面是c++的approach.
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
if(!head)
return false;
ListNode* fast = head;
ListNode* slow = head;
while(fast->next != NULL && fast->next->next != NULL){
fast = fast->next->next; // 走两格
slow = slow->next; // 走一格
if(fast == slow)
return true;
}
return false;
}
};