https://leetcode-cn.com/problems/linked-list-cycle/[题目地址]
思路:
- 用Set遍历ListNode
public boolean hasCycle(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;
}
- 快慢指针。慢指针走一步,快指针走两步,如果有环,则一定会相遇。慢指针走一圈,快指针走两圈回到起点。
public static boolean hasCycle(ListNode head) {
ListNode fast = head;
ListNode slow = head;
while(fast != null && fast.next != null){
slow = slow.next;
fast = fast.next.next;
if(slow == fast)return false;
}
return true;
}