一、需求
- 给定一个链表,判断链表中是否有环。
输入:head = [3,2,0,-4], pos = 1 输出:true 解释:链表中有一个环,其尾部连接到第二个节点。
提示:
- 链表中节点的数目范围是
[0, 104]
-105 <= Node.val <= 105
pos
为-1
或者链表中的一个 有效索引
二、快慢指针
2.1 思路分析
- 判断一个链表是否有环可以利用快慢指针解决,思路与上一篇快乐数:https://blog.csdn.net/Sruggle/article/details/113744141一致;
2.2 代码实现
public class Solution {
public boolean hasCycle(ListNode head) {
if(head == null) return false;
ListNode fast = head.next;
ListNode slow = head;
while(fast != null && fast.next != null && fast != slow) {
fast = fast.next.next;
slow = slow.next;
}
return fast != null && fast.next != null;
}
}
2.3 复杂度分析
- 时间复杂度为O(N);
- 空间复杂度为O(1);
三、哈希表
3.1 思路分析
- 思路同上一篇快乐数:https://blog.csdn.net/Sruggle/article/details/113744141一致;
- 即将链表中的节点存进哈希表中,若出现相同元素,就说明有环;
3.2 代码实现
public class Solution {
public boolean hasCycle(ListNode head) {
Set<ListNode> hs = new HashSet<>();
ListNode p = head;
while(p != null) {
if(hs.contains(p)) {
return true;
}
hs.add(p);
p = p.next;
}
return false;
}
}
3.3 复杂度分析
- 时间复杂度为O(N);
- 空间复杂度为O(N);