LeetCode Linked List Cycle (Floyd判圈算法)

题目描述:https://oj.leetcode.com/problems/linked-list-cycle/

给一个链表,Floyd判圈可在O(n)的时间复杂度,O(1)的空间复杂度内判定其中有没有环。


package LinkedListCycle;

public class Solution {
	 class ListNode{
		 int val;
		 ListNode next;
		 ListNode(int x){
			 val = x;
			 next = null;
		 }
	 }
	 public boolean hasCycle(ListNode head) {
		 	if(head==null) return false;
	        ListNode slowPtr = head;
	        ListNode fastPtr = head;
	        boolean flag = true;
	        do{
	        	if(fastPtr.next == null ||fastPtr.next.next == null){
	        		flag = false;
	        		break;
	        	}
	        	slowPtr = slowPtr.next;
	        	fastPtr = fastPtr.next.next;
	        }while(slowPtr != fastPtr);
	        return flag;
	 }
}


你可能感兴趣的:(LeetCode)