难度: Easy
内容描述
给定一个链表,确定其中是否有一个循环。
跟进:
你能在不占用额外空间的情况下解决它吗?
思路 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;
}
}