难度: Easy
原题连接
内容描述
Given a linked list, determine if it has a cycle in it.
Follow up:
Can you solve it without using extra space?
思路 1 - 时间复杂度: O(N)- 空间复杂度: O(1)******
快慢指针
java
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null){
return false;
}
ListNode fast = head;
ListNode slow = head;
while (fast != null && slow != null && fast.next != null){
fast = fast.next.next;
slow = slow.next;
if (slow == fast){
return true;
}
}
return false;
}
}