題目:
Given a linked list, determine if it has a cycle in it.
思路:
快慢指針
代碼:
class Solution {
public:
/*
* @param head: The first node of linked list.
* @return: True if it has a cycle, or false
*/
bool hasCycle(ListNode * head) {
// write your code here
if(head == NULL || head->next == NULL)
return false;
ListNode *fast = head;
ListNode *slow = head;
while(fast->next != NULL && fast->next->next != NULL){
fast = fast->next->next;
slow = slow->next;
if(slow == fast)
return true;
}
return false;
}
};