Thursday, November 5, 2015

[leetcode]Linked List Cycle

Classic problem, use two pointers.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode fast = head.next == null?null:head.next.next;
        ListNode slow = head;
        while (fast != null){
            if (slow == fast) return true;
            fast = fast.next == null?null:fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}

No comments:

Post a Comment