当前位置:编程学习 > JAVA >>

Linked List Cycle @LeetCode

[java] view plaincopy
package Level2;  
  
import Utility.ListNode;  
  
/** 
 * 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? 
 * 
 */  
public class S127 {  
  
    public static void main(String[] args) {  
  
    }  
      
    // 经典快慢指针找环问题  
    public boolean hasCycle(ListNode head) {  
        ListNode slow = head, fast = head;  
          
        while(true){  
            if(fast==null || fast.next==null || slow==null){  
                return false;  
            }  
              
            fast = fast.next.next;  
            slow = slow.next;  
              
            if(fast == slow){  
                return true;  
            }  
        }  
    }  
  
}  

 

补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,