Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
转自https://leetcode.com/discuss/32906/o-1-space-solution
方法:
使用两个指针:slow和fast。它俩都从head出发,fast指针每次走两步,slow指针每次走一步。若没有循环,一定fast指针率先遇到null;若有循环,fast和slow一定能相遇。
/**
* Definition for singly-linked list.
* class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null)
return false;
ListNode slow = head;
ListNode fast = head;
while(fast.next != null && fast.next.next != null){
if(fast.next == slow){
return true;
}
fast = fast.next.next;
slow = slow.next;
}
return false;
}
}