http://oj.leetcode.com/problems/linked-list-cycle/
老题,快慢指针。
/**
* 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) {
ListNode *fast = head;
ListNode *slow = head;
do {
if (fast == NULL || fast->next == NULL) return false;
fast = fast->next->next;
slow = slow->next;
} while (fast != slow);
return true;
}
};