难度:easy
方法一:
快慢指针,因为快指针每次都比慢指针多移动一个节点,所以如果有环的话他们一定会相遇;
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;
}
}
复杂度分析:
- 时间复杂度:O(n)
- 空间复杂度: O(1)
方法二:
hashset记录遍历节点,如果有重复的节点,则说明有环;
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode cur = head;
Set<ListNode> set = new HashSet<ListNode>();
while (cur != null) {
if (set.contains(cur)) {
return true;
} else {
set.add(cur);
}
cur = cur.next;
}
return false;
}
}
复杂度分析:
- 时间复杂度:O(n)
- 空间复杂度:O(n),哈希表的开销