/*
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
//Runner Technique
//slow: p1 move one step at time
//fast: p2 move two steps at time.
// if two points are meet, hasCycle
//else noCycle
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
if(head.next==null) return false;
ListNode slow=head;
ListNode fast=head;
//check whether reach the end of LinkedList or encounter the slow point
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
if(slow==fast) return true;
}
return false;
}
}
Linked List Cycle Java
最新推荐文章于 2018-11-04 23:25:23 发布