题目:
https://leetcode-cn.com/problems/linked-list-cycle/
import java.util.ArrayList; import java.util.List; public class _141_HasCycle { // 哈希散列表 public boolean hasCycle(ListNode head) { List<ListNode> list = new ArrayList<>(); while(head != null) { if(list.indexOf(head) == -1) { list.add(head); } else{ return true; } head = head.next; } return false; } // 快慢指针法 public boolean hasCycle1(ListNode head) { if (head == null || head.next == null) { return false; } ListNode fast = head.next; ListNode slow = head; while(slow != fast) { if(fast == null || fast.next == null) { return false; } slow = slow.next; fast = fast.next.next; } return true; } }