1.本算法的核心之处在于 快指针每次后移2个单位,慢指针每次后移1个单位。
a.由于快指针每次的运动量为2个单位,只要判断当前位置和下一位置中是否出现空,若为空,则证明链表不含有环!
b.如果一直执行下去还没有出现快指针指向空的事件发生,若其中有环,则快指针会与慢指针重合,即指向同一位置,由于快指针运动2个单位,则还是判断快指针的当前位置与下一位置中是否与慢指针指向同一对象,若为同一对象,则证明必然有环。
c.在本回合中若a,b均为出现停止状态,那么迭代,fast = fast.getNext().getNext(); slow = slow.getNext();
以下为代码:
Public Node 节点类
public class Node { private int value; private Node next; public int getValue() { return value; } public void setValue(int value) { this.value = value; } public Node getNext() { return next; } public void setNext(Node next) { this.next = next; } public void display(){ System.out.println(this.value +""); } }
测试方法类 NodeRun
public class NodeRun { static{ System.out.println("静态块执行完毕"); } public static void main(String[] args){ Node node1 = new Node(); Node node2 = new Node(); Node node3 = new Node(); Node node4 = new Node(); Node node5 = new Node(); node1.setValue(1); node2.setValue(2); node3.setValue(3); node4.setValue(4); node5.setValue(5); node1.setNext(node2); node2.setNext(node3); node3.setNext(node4); node4.setNext(node5); node5.setNext(node3); //遍历 // Node node = node1; // while(node != null){ // node.display(); // node = node.getNext(); // } //快慢指针设计,判断单链表是否有循环 Node first = node1; Node fast = first.getNext().getNext(); Node slow = first.getNext(); int count = 0; while(true){ count ++; if(fast == null || fast .getNext() == null){ System.out.println("No Circle and this is the No." + count + " times comparing!") ; break; }else if(fast == slow || fast.getNext() == slow){ System.out.println("Do Have Circle and this is the No." + count + " times comparing!") ; break; }else{ fast = fast.getNext().getNext(); slow = slow.getNext(); System.out.println("this is the No." + count +" times comparing! "); } } } }
测试结果如下:
静态块执行完毕 this is the No.1 times comparing! Do Have Circle and this is the No.2 times comparing!