题目
这道题是 leetcode 的第 141 题
给定一个链表,判断链表中是否有环
对应的题目 环形链表
题目解析
方法 1:暴力 + 哈希表
遍历链表,放到 hash 表中,可以是 set,然后在遍历过程中,去判断 set 中是否存在,如果存在说明又走回来了,即有环
时间复杂度:O(n)
空间复杂度:O(n)
public static boolean hashCycle(ListNode head) {
Set<ListNode> set = new HashSet<>();
while (head != null) {
if (set.contains(head)) {
return true;
} else {
set.add(head);
}
head = head.next;
}
return false;
}
方法 2:快慢指针
快慢指针,不同速度的两个指针,如果链表有环肯定会相遇
时间复杂度:O(n)
空间复杂度:O(1)
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;
}