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:
bool hasCycle(ListNode *head) {
ListNode* step1 = head;
ListNode* step2 = head;
while(step2 != NULL && step1->next != NULL && step2 -> next != NULL )
{
step1 = step1->next;
step2 = step2->next->next;
if (step1 == step2)
return true;
}
return false;
}
};
最开始总有 run time error, 是因为缺少了
step2 != NULL
不需要对step1判断,因为step2 总是跑的比step1快