问题描述
判断给定的链表中是否有环
扩展:
你能给出不利用额外空间的解法么?
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
解决方案
使用快慢指针,如果两个指针相遇了,那么就存在环,否则不存在
注意考虑head为空的情况
class Solution {
typedef ListNode node;
public:
bool hasCycle(ListNode *head) {
if(head ==NULL ||head->next==NULL)return false;
node *chaser=head;
node *runner = head;
while(runner!=NULL && runner->next!=NULL){
chaser = chaser->next;
runner = runner->next->next;
if(chaser==runner)return true;
}
return false;
}
};