Blind 75

Linked List Cycle

Problem
LC 141
Category
Linked List
File
blind75_LC141LinkedListCycle.java
Path
pkg5leetcode/blind75/blind75_LC141LinkedListCycle.java
Package
pkg5leetcode.blind75
Command
java pkg5leetcode/blind75/blind75_LC141LinkedListCycle.java
Approach
Floyd slow/fast pointers detect cycle.
Complexity
Time O(n), Space O(1)

LeetCode solutions

There is no in-browser runner. This is the file from the curriculum, unchanged.

pkg5leetcode/blind75/blind75_LC141LinkedListCycle.java
1package pkg5leetcode.blind75;2 3/*4 * Linked List Cycle | LC 1415 * APPROACH: Floyd slow/fast pointers detect cycle.6 * COMPLEXITY: Time O(n), Space O(1)7 */8public class blind75_LC141LinkedListCycle {9    /** Same shape as pkg5leetcode/common/ListNode.java (nested for single-file runs). */10 11    static class ListNode {12        int val;13        ListNode next;14        ListNode(int val) { this.val = val; }15    }16 17    static boolean hasCycle(ListNode head) {18        ListNode slow = head, fast = head;19        while (fast != null && fast.next != null) {20            slow = slow.next;21            fast = fast.next.next;22            if (slow == fast) return true;23        }24        return false;25    }26 27    public static void main(String[] args) {28        ListNode n3 = new ListNode(3);29        ListNode head = new ListNode(1);30        head.next = new ListNode(2);31        head.next.next = n3;32        n3.next = head.next;33        check(hasCycle(head), "case1");34        ListNode solo = new ListNode(1);35        check(!hasCycle(solo), "case2");36        System.out.println("all tests passed");37    }38 39    static void check(boolean cond, String name) {40        if (!cond) throw new AssertionError("FAILED: " + name);41        System.out.println("  PASS " + name);42    }43}