方法一 遍歷
循環鏈表,查找鏈表節點是否重復出現
public boolean hasCycle(ListNode head) {Set<ListNode> set = new HashSet<>(); if (head == null) return false; while (head != null) {if (set.contains(head)) {return true;}set.add(head);head = head.next;}return false;}
方法二 快慢指針法
// 處理邊界情況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;