Given a linked list, determine if it has a cycle in it.
Follow up:
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:
bool hasCycle(ListNode *head) {
ListNode *oneStep = head;
ListNode *twoStep = head;
while (oneStep && twoStep->next) {
oneStep = oneStep->next;
twoStep = twoStep->next->next;
if (oneStep == NULL || twoStep == NULL) {
return false;
}
if (oneStep == twoStep) {
return true;
}
}
return false;
}
};