题目描述:
思路:最简单的做法就是快慢指针。但官方给出了用哈希表的方法。分析了一下,哈希表的方法空间复杂度高一点。虽然两种方法的时间复杂度都是O(n)但是哈希表仍然会比快慢指针的方法要小且稳定。
快慢指针
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head;
ListNode fast = head.next;
while (slow != fast) {
if (fast == null || fast.next == null) {
return false;
}
slow = slow.next;
fast = fast.next.next;
}
return true;
}
}