Sunday, January 4, 2015

Linked List Cycle (LeetCode Linked List)

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

Idea: Like the minute hand will always catch up the hour hand on the clock, a faster running pointer will always catch up the slower running pointer if there is a cycle in the linked list. This is a classic math problem and it has many applications, e.g. blind channel hopping.

Time: O(n) Space: O(1)

Code:
 public class Solution {  
   public boolean hasCycle(ListNode head) {  
     if(head==null||head.next==null)  
       return false;  
     ListNode slower=head;  
     ListNode faster=head;  
     while(faster.next!=null)  
     {  
       faster=faster.next;  
       if(faster==slower)  
         return true;  
       slower=slower.next;  
       faster=faster.next;  
       if(faster==null)  
         return false;  
     }  
     return false;  
   }  
 }  

No comments:

Post a Comment