题目:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
//快慢指针。时间复杂度O(n),空间复杂度O(1)
bool hasCycle(ListNode *head) {
if(NULL == head || NULL == head->next) return false;//保证后面fast不为空,循环结束条件fast->next才不会出错
ListNode *slow = head;//注意初始化
ListNode *fast = head->next;//注意初始化
while(fast && fast->next && slow != fast){
slow = slow->next;//一次一步
fast = fast->next->next;//一次两步
}
return slow == fast ? true : false;
}
};