题目地址: http://www.lintcode.com/zh-cn/problem/linked-list-cycle/
/** * Definition of ListNode * class ListNode { * public: * int val; * ListNode *next; * ListNode(int val) { * this->val = val; * this->next = NULL; * } * } */ 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 bool res = false; ListNode *slow = head; ListNode *fast = slow; if(slow == NULL || fast->next == NULL) return res; fast = fast->next; if(fast->next == NULL) return res; fast = fast->next; while(slow && fast) { if(slow == fast) return true; if(fast->next == NULL || fast->next->next == NULL) return res; fast = fast->next->next; slow = slow->next; } return res; } };