力扣100- 环形链表
方法一 遍历
循环链表,查找链表节点是否重复出现
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;