Linked List Cycle

Given a linked list, determine if it has a cycle in it.

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.next;
        ListNode slow = head;
        //警惕空值!!!
        while (fast != null && fast.next != null) {
            if (fast == slow) {
                return true;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}
点赞