141. Linked List Cycle

ๅฟซๆ…ขๆŒ‡้‡, ๆฏ”่ผƒ็›ธ็ญ‰ๆ˜ฏๆฏ”่ผƒ็‰ฉไปถๅ–”๏ผๆณจๆ„๏ผ

time: O(n)

space:O(1)

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public boolean hasCycle(ListNode head) {
        if (head == null) return false;
        ListNode runner = head;
        ListNode walker = head;

        while (walker.next != null && runner.next != null && runner.next.next != null) {
            walker = walker.next;
            runner = runner.next.next;
            if (walker == runner) return true; // compare pbject address
        }
        return false;
    }
}

Last updated