Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
快慢指针,1个每次走一步,1个每次走两步,若两指针相遇,说明有环
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode pre = head;
ListNode post = head;
while(post!=null&&post.next!=null){
post=post.next.next;
pre = pre.next;
if(pre==post)
return true;
}
return false;
}
}