由买买提看人间百态

topics

全部话题 - 话题: hasloop
(共0页)
O******i
发帖数: 269
1
来自主题: JobHunting版 - std::list如何检测环?
Please implement the loop detection for std::list, like hasLoop(std::list
alist)
如果是普通链表找环,可以用两个指针,一快一慢。能套用到这题么?具体code如何写?
bool hasLoop(std::list alist)
{
blablabla
}
k*******t
发帖数: 144
2
来自主题: JobHunting版 - 问一道google的面试题
两个指针(slow, fast)就够啦,判断list有无loop也不需要额外空间。贴了个代码,比
较ugly, 凑合着看吧
bool hasLoop(int arr[], int len){

int slow = 0;
int fast = 0;
int cur = 0;
while(cur < len)
{
if(arr[slow] != -1)
{
slow = arr[slow];
}
else
{
++slow;
fast = slow;
cur = slow;
continue;
}

int i = 0;
while(i < 2 && arr[fast] != -1)
{
fast = arr[fast];
... 阅读全帖
(共0页)