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