这是一道面试题,要求用最简洁的代码写出判别单链表中是否存在环。我是这样做的,可将单链表视作一种简化的图,在依照链表指针域遍历链表时,保留每个结点的入度,若在到达尾结点之前出现入度为2的结点,说明链表中存在环,同时终止遍历。
/*
* 判别单链表中是否存在环
*/
#include <map>
using std::map;
typedef int elem_type;
struct Node
{
elem_type data;
Node * next;
};
bool has_loop( Node * h )
{
bool exist = false;
map<long, int> dict; // key为结点地址
Node * p = h->next;
while( p != NULL )
{
++dict[p];
if( dict[p] == 2 )
{
exist = true;
break;
}
p = p->next;
}
return exist;
}