一、题目
- 141. 环形链表 - 力扣(LeetCode)
给你一个链表的头节点
head
,判断链表中是否有环。如果链表中有某个节点,可以通过连续跟踪
next
指针再次到达,则链表中存在环。 为了表示给定链表中的环,评测系统内部使用整数pos
来表示链表尾连接到链表中的位置(索引从 0 开始)。注意:pos
不作为参数进行传递 。仅仅是为了标识链表的实际情况。如果链表中存在环 ,则返回
true
。 否则,返回false
。
二、思路
- 链表肯定要遍历,但提供的链表为环形链表;
- 环形链表意味着不存在 p.next == null 这种情况,所以不能只用 p.next != null 作为循环终止条件;
- 解法一:题目中指出链表中节点的数目范围是 [0, 10000] ,则只需要遍历完整个链表且遍历次数达到10000次,如果head没有走到尾部,说明必定有环;
- 解法二:每走过一个节点将其设置为一个特殊值,有环则必会重走一遍,此时环中所有结点的 val 均为特殊值;
- 解法三:设置一个哈希表,将遍历过的结点 val 值存入表中,每次走到新结点时判断一次表内是否有相同元素,如果有则有环;
- 解法四:Floyd判圈算法(龟兔赛跑算法),维护两个指针,如果有环则快指针一定会与慢指针相遇;
三、解法
【不严谨】解法一
public class Solution {
public boolean hasCycle(ListNode head) {
int count = 10000;
while (head != null && count > 0) {
head = head.next;
count--;
}
return head == null ? false : true;
}
}
【不严谨】解法二
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
while (head.next != null && head.val != Integer.MAX_VALUE) {
head.val = Integer.MAX_VALUE;
head = head.next;
}
return head.val == Integer.MAX_VALUE ? true : false;
}
}
解法三
public class Solution {
public boolean hasCycle(ListNode head) {
HashSet<ListNode> set = new HashSet<>();
while (head != null) {
// 原始版
// if (set.contains(head)) {
// return true;
// }
// set.add(head);
// 优化版 (已有相同元素则无法插入)
if (!set.add(head)) {
return true;
}
head = head.next;
}
return false;
}
}
解法四
public class Solution {
public boolean hasCycle(ListNode head) {
if (head == null || head.next == null) {
return false;
}
ListNode slow = head, fast = head;
while (fast.next != null && fast.next.next != null) {
slow = slow.next;
fast = fast.next.next;
if (slow == fast) {
return true;
}
}
return false;
}
}