题目描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
寻找链表中的环,用两个指针,一个一次走一步,另一个一次走两步,如果相遇则存在环,反之则不存在。
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow = head;
ListNode fast = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(fast == slow)
return true;
}
return false;
}
}