1. 程式人生 > 實用技巧 >重學資料結構(五)——判斷連結串列是否為環形

重學資料結構(五)——判斷連結串列是否為環形

判斷連結串列是否為環形

思路:
定義兩個指標fast、slow, 一次迴圈中讓fast走兩步,slow走一步。
看兩者有無相遇的機會(判斷兩個指標是否為同一節點),相等則為同一個節點-->連結串列為環形

判斷連結串列是否為環形的實現

package com.codezs.datastruct.mylinkedlist;

public class LinkListCircle {
    
    //判斷連結串列是否為環形
    public boolean checkCircle(Node node){
        //如果該節點為null 則不為環形連結串列
        if (node == null) return false;

        Node fast = node.next;
        Node slow = node;

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

            if (fast == slow) return true;
        }
        return false;
    }
}

節點類的實現

package com.codezs.datastruct.mylinkedlist;

public class Node<T> {
    T data;
    Node<T> next;

    Node(Node<T> next) {
        this.next = next;
    }

    public Node(T data, Node<T> next) {
        this.data = data;
        this.next = next;
    }

    public T getData(){
        return data;
    }
    public Node<T> getNext(){
        return next;
    }
    public void setNext(Node<T> next){this.next = next;}

}