环形链表
思路1:两个指针cur1,cur2 同时从起点开始走,cur1每次只走一步,计数器pos1就自增1。cur1每走一步,cur2就从起点开始走,当两个指针相遇时,就判断pos1和pos2是否相等。若相等cur2回到起点位置, pos2也会置为0,重新计数。直到最后步数不相同且两个指针指向同一个节点,就说明该链表是环形链表。
class Solution {
public:
bool hasCycle(ListNode *head)
{
ListNode* cur1=head;
ListNode* cur2=head;
int pos2=0;int pos1=0;
while(cur1)
{
cur2 = head;
pos2=0;//步数相同且两个指针指向同一个节点就重新开始计数
while(cur2)
{
if(cur1==cur2)
{
if(pos1==pos2){
break;
}
else{
return true;
}
}
cur2=cur2->next;
pos2++;
}
cur1=cur1->next;
pos1++;
}
return false;
}
};
思路2:这个思路的话就很简单了,就是采用快慢指针的思路,慢指针走一步,快指针走两步,两个指针会在环中相遇,说明该链表有环。则反之。
class Solution {
public:
bool hasCycle(ListNode *head)
{
ListNode *cur1=head;
ListNode *cur2=head;
while(cur1&&cur2&&cur2->next)
{
cur1=cur1->next;//慢指针走一步
cur2=cur2->next->next;//快指针走两步
if(cur1==cur2)
{
return true;//两个指针相遇说明有环
}
}
return false;
}
};