Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路:设置一个快慢指针,同时指向头结点,快指针一次走2步,慢指针一次走1步,如果是循环的,快指针会追上慢指针。
代码如下(已通过leetcode)
public class Solution {
public boolean hasCycle(ListNode head) {
if(head==null) return false;
ListNode fast=head;
ListNode slow=head;
while(slow.next!=null&&fast.next!=null&&fast.next.next!=null) {
slow=slow.next;
fast=fast.next.next;
if(slow==fast) return true;
}
return false;
}
}