给定一个链表,判断链表中是否有环。
如果链表中有某个节点,可以通过连续跟踪 next 指针再次到达该节点,则链表中存在环
如果链表中存在环,则返回 true 。 否则,返回 false 。
解法一:哈希表
public static boolean hasCycle(ListNode head) {Set<ListNode> seen = new HashSet<ListNode>();while (head != null) {if (!seen.add(head)) {return true;}head = head.next;}return false;}
解法二:双指针
public static boolean hasCycle2(ListNode head) {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;}
