天天看點

環形連結清單(判斷一個連結清單是否有環)(Java實作)

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null){
            return false;
        }
        ListNode slow = head,fast = head.next;    //如果有環,則必會相遇。
        while(fast != null && fast.next != null){ //fast==null時,意味着已經周遊到連結清單的尾節點,快慢指針未相遇,無環
            slow = slow.next;
            fast = fast.next.next;
            if(fast == slow) return true;
        }
        return false;
    }
}