标签:blog div sp 代码 log c ad r as
1、题目
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
2、思路
设置两个指针,一个每次走一步,另一个每次走两步。走两步的一定会追上走一步的。
3、代码
bool hasCycle(ListNode *head)
{
bool cycle = false;
if(head==NULL)
{
return false;
}
ListNode *low_cursor = head;
if(head->next==NULL)
{
return false;
}
ListNode *fast_cursor = head->next;
while(fast_cursor->next != NULL)
{
if(fast_cursor==low_cursor)
{
cycle = true;
break;
}
else
{
low_cursor = low_cursor->next;
fast_cursor = fast_cursor->next;
if(fast_cursor==low_cursor)
{
cycle = true;
break;
}
if(fast_cursor->next==NULL)
{
break;
}
else
{
fast_cursor = fast_cursor->next;
if(fast_cursor==low_cursor)
{
cycle = true;
break;
}
}
}
}
return cycle;
}
标签:blog div sp 代码 log c ad r as
原文地址:http://www.cnblogs.com/erli11/p/3966989.html