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) {
if(head == NULL)
return false;
ListNode *pre = head;
ListNode *cur = head;
while(pre != NULL && pre->next != NULL)
{
pre = pre->next->next;
cur = cur->next;
if(pre == cur)
return true;
}
return false;
}
};

做题是两个细节:

1. 上来判断head是否为空

2. 循环的条件是(pre != NULL && pre->next != NULL)