單鏈表中是否出現環狀,使用快慢指針算法。

1.本算法的核心之處在於 快指針每次後移2個單位,慢指針每次後移1個單位。node

a.因爲快指針每次的運動量爲2個單位,只要判斷當前位置和下一位置中是否出現空,若爲空,則證實鏈表不含有環!算法

b.若是一直執行下去尚未出現快指針指向空的事件發生,若其中有環,則快指針會與慢指針重合,即指向同一位置,因爲快指針運動2個單位,則仍是判斷快指針的當前位置與下一位置中是否與慢指針指向同一對象,若爲同一對象,則證實必然有環。測試

c.在本回閤中若a,b均爲出現中止狀態,那麼迭代,fast = fast.getNext().getNext(); slow = slow.getNext();this

 

如下爲代碼:spa

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! ");
            }                        
        }
    }

}

測試結果以下:code

靜態塊執行完畢
this is the No.1 times comparing! 
Do Have Circle and this is the No.2 times comparing!
相關文章
相關標籤/搜索