2014年4月28日 星期一

[LeetCode] Linked List Cycle

Problem:
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution:O(n)
public class Solution {
    public boolean hasCycle(ListNode head) {
        ListNode slow = head;
 ListNode faster = head;
     
 while(faster!=null && faster.next!=null && faster.next.next!=null ){
     if(faster.next == slow || faster.next.next == slow){
         return true;
     }
     slow = slow.next;
     faster = faster.next.next;
 }
 
        return false;
    }
}

沒有留言:

張貼留言