C#判断单链表是否有环
static bool IfCircle(SingleLinkNode node)
{
SingleLinkNode slowNode = node, fastNode = node;
while(node.NextNode != null)
{
slowNode = slowNode.NextNode; //相当于步长为1的节点指针
fastNode = fastNode.NextNode; //相当于步长为2的节点指针
if (fastNode.NextNode!= null)
fastNode = fastNode.NextNode;
else
return false;
node = node.NextNode;
if (slowNode == fastNode)
return true; //如果相交,证明有环
}
return false;
}