题目:判断一个链表中是否有环
这个题目很容易被面试官拿来考察代码能力,解题技巧就是定义两个指针,一前一后,一个每次走一步,另一个每次走两步,看最后两个指针是否会相遇
class Solution {
public:
bool hasCycle(ListNode *head) {
if(head==NULL||head->next==NULL)
return false;
ListNode *tmp1=head->next;
ListNode *tmp2=head->next->next;
while(tmp2&&tmp2->next)
{
if(tmp1==tmp2)
return true;
tmp1=tmp1->next;
tmp2=tmp2->next->next;
}
return false;
}
};