Linked List Cycle

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

 1 public class Solution {
 2     public boolean hasCycle(ListNode head) {
 3         if(head==null) return false;
 4         ListNode fast = head;
 5         ListNode slow = head;
 6         while(fast!=null){
 7             slow = slow.next;
 8             fast = fast.next;
 9             if(fast==null)
10                 return false;
11             fast = fast.next;
12             if(fast==slow) return true;
13         }
14         return false;
15     }
16 }
View Code

 

posted @ 2014-02-22 13:08  krunning  阅读(139)  评论(0)    收藏  举报