[Microsoft] Linked List Cycle

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @return: True if it has a cycle, or false
     */
    public boolean hasCycle(ListNode head) {  
        if(head==null){
            return false;
        }
        
        ListNode fast=head;
        ListNode slow=head;
        while(fast.next!=null && fast.next.next!=null){        //只有保證fast.next不爲空,纔能有fast.next.next
            slow=slow.next;
            fast=fast.next.next;
            if(slow==fast){                                    //最終slow追上fast
                return true;
            }
        }
        return false;
    }   
}

發佈了102 篇原創文章 · 獲贊 2 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章