LeetCode141-环形链表
LeetCode141-环形链表
哈希表
| public boolean hasCycle1(ListNode head) { Set<ListNode> seen = new HashSet<ListNode>(); while (head != null) { if (!seen.add(head)) { return true; } head = head.next; } return false; }
|
快慢指针
| public boolean hasCycle(ListNode head) { if (head == null || head.next == null) return false; ListNode k = head.next; ListNode m = head; while (k != null && k.next != null) { if (k == m) return true; m = m.next; k = k.next.next; } return false; }
|