2015年10月15日星期四

Leetcode 141 Linked List Cycle

Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
Solution 1: use fast/slow pointers. If they meet, means there is cycle.
 public class Solution {  
   public boolean hasCycle(ListNode head) {  
     ListNode fast=head, slow=head;  
     while (fast!=null && fast.next!=null) {  
       fast=fast.next.next;  
       slow=slow.next;  
       if (fast==slow) return true;  
     }  
     return false;  
   }  
 }  

没有评论:

发表评论