Given a linked list, determine if it has a cycle in it.
Follow up: Can you solve it without using extra space?
思考:快慢指针,快指针一次走两步,慢指针一次一步。若快指针跟慢指针指向同一个结点,则有环。若快指针到达链表末尾即指向NULL,说明没有环。
/**
* 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) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
if(!head||!head->next) return false;
ListNode *p=head;
ListNode *q=p->next;
while(q&&q->next)
{
if(p==q) return true;
else
{
q=q->next->next;
p=p->next;
}
}
return false;
}
};