版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
LeetCode141 环形链表
给定一个链表,判断链表中是否有环。
为了表示给定链表中的环,我们使用整数 pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。 如果 pos
是-1
,则在该链表中没有环。
第一种思路:设置一个超时时间,在指定时间内一直向后移动指针
-
指针变为null 说明到达链表尾部,则无环
-
超时:链表有环
这种思路弊端很明显,第一超时时间难以界定。第二,耗时
第二种思路:使用set辅助。 向后遍历链表,每遍历一个节点,先判断是否在集合中,如果不在则放入set 否则则有环,如果知道遍历结束也没有重复则无环
时间复杂度O(N),空间复杂度O(N)
public boolean hasCycle(ListNode head) {
Set<ListNode> visited = new HashSet<>();
while (head != null) {
if (visited.contains(head)) {
return true;
} else {
visited.add(head);
}
head = head.next;
}
return false;
}
第三种思路:快慢指针,快指针一次走两个节点,慢指针一次走一个节点,如果快指针与慢指针相遇,则有环 如果快指针率先到达链表尾部则无环。
public boolean hasCycleTwo(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode fast = head;
ListNode slow = head;
while (slow != fast) {
if (fast.next == null || fast.next.next == null) {
return false;
}
fast = fast.next.next;
slow = slow.next;
}
return true;
}