JJY

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;
        }

posted on 2010-01-27 20:32  MikeJia  阅读(784)  评论(0编辑  收藏  举报

导航