方法一:快慢指针
- 容易产生误解的是,快指针每次都要比慢指针多走1一步,也就是两者速度是有差异的,而不是两者开始的启动位置有差异,只有速度有差异才能最终相遇,这个有时候可能会想错!
- 原理简单,主要是边界判断,什么时候退出
- 快慢指针的起点其实是相差一个位置的,这个要注意
package com.company.linked;
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;
}
}
方法一:哈希表
- 存在重复的节点则表示有环,主要是耗费空间
package com.company.linked;
import java.util.HashSet;
import java.util.Set;
public class Solution1 {
public boolean hasCycle(ListNode head) {
Set<ListNode> seen = new HashSet<ListNode>();
while (head != null) {
if (!seen.add(head)) {
return true;
}
head = head.next;
}
return false;
}
}