141. Linked List Cycle

经典的套环问题,后面的套环题变式都是用Array的index来代表pointer以此判断是否重复element之类的。。

快慢指针相遇。

time: O(n)
space: O(1)

public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null || head.next == null) return false;
        ListNode slow = head;
        ListNode fast = head;
        while (fast != null && fast.next != null) {
            slow = slow.next;
            fast = fast.next.next;
            if (slow == fast) return true;
        }
        return false;
    }
}
posted @ 2016-11-04 11:56  哇呀呀..生气啦~  阅读(72)  评论(0)    收藏  举报