Problem

Given a linked list, determine if it has a cycle in it.

Example
Given -21->10->4->5, tail connects to node index 1, return true

思路一

  • use hashset
    public boolean hasCycle(ListNode head) {  
        HashSet<ListNode> hash = new HashSet<>();
        while (head != null) {
            if (hash.contains(head)) {
                return true;
            }
            hash.add(head);
            head = head.next;
        }
        return false;
    }

思路二

  • fast & slow node
    public boolean hasCycle(ListNode head) {  
        if (head == null) return false;
        ListNode slow = head;
        ListNode fast = head.next;

        while (fast != null && fast.next != null) {
            if (fast == slow) return true;
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }

results matching ""

    No results matching ""