0

我正在阅读算法书并自己实现书中写的所有方法。我学习了以龟兔算法而闻名的弗洛伊德的寻环算法,这里是实现。请让我知道我是否执行不正确或有任何改进建议。谢谢 !

 public class LinkedListLoops {

    private Node head;
    private Node tail;

    public void floydCycle(){
            if(node == null) throw new NullPointerException();

            Node temp = head;
            Node fast = head;
            Node slow = head;

            while(fast.next != null){
                slow = slow.next;
                if(fast.next.next != null){
                    fast = fast.next.next;
                }

                if(fast == slow){
                    fast = temp;
                    while(fast != slow){
                      fast = fast.next;
                    }
                    while(fast.next != slow){
                        fast = fast.next;
                    }
                    fast.next = null;
                }
            }
        }
   }
4

0 回答 0