Leetcode141. Linked List Cycle

/**
 * 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) return false;
        
        ListNode slow = head, fast = head.next;
        while(fast!=null){
            if(slow==fast) return true;
            slow = slow.next;
            if(fast.next==null||fast.next.next==null) return false;
            fast = fast.next.next;
        }
        return false;
    }
}
/**
 * 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) return false;
        
        ListNode slow = head, fast = head.next;
        while(fast!=slow){
            if(fast==null||fast.next==null||fast.next.next==null) return false;
            fast = fast.next.next;
            slow = slow.next;
        }
        return true;
    }
}

Runtime: 0 ms, faster than 100.00% of Java online submissions for Linked List Cycle.
Memory Usage: 37.6 MB, less than 96.65% of Java online submissions for Linked List Cycle.

posted @ 2019-03-29 00:04  大胖子球花  阅读(63)  评论(0)    收藏  举报