1. 程式人生 > >資料結構——單鏈表(環)

資料結構——單鏈表(環)

一、環

標題

 

二、建立環

//建立環
    public void createLoop(){
        Entry cur = this.head;
        while(cur.next != null){
            cur = cur.next;
        }
        Entry cur2 = this.head.next.next.next;
        cur.next = cur2;//和第三個資料結點構成一個環
    }

三、判斷是否有環

//判斷一個單鏈表中是否有環
    public boolean isLoop(){
        //快指標和慢指標從head出發
        Entry fast = this.head;
        Entry slow = this.head;
        while(fast != null && fast.next != null){
            //fast每走兩步,slow走一步
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast){//有環的話,fast和slow遲早會相遇
                return true;
            }
        }
        //沒有相遇就沒有環
        return false;
    }

四、換的入口點

    //環的入口點
    public int enterEntry(){
        Entry fast = this.head;
        Entry slow = this.head;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast){
                break;
            }
        }
        slow = this.head;
        while(fast != slow){
            fast = fast.next;
            slow = slow.next;
        }
        return slow.data;
    }

五、環的長度

    //環的長度
    public int loopLength(){
        Entry fast = this.head;
        Entry slow = this.head;
        boolean flag = false;//標記
        int len = 0;
        while(fast != null && fast.next != null){
            fast = fast.next.next;
            slow = slow.next;
            if(slow == fast && flag == true){
                break;
            }

            if(slow == fast && flag == false){
                flag = true;//第一次相遇將flag置為true
            }
            if(flag == true){
                len ++;
            }
        }
        return len;
    }