All Downloads are FREE. Search and download functionalities are using the official Maven repository.

g0101_0200.s0141_linked_list_cycle.Solution Maven / Gradle / Ivy

The newest version!
package g0101_0200.s0141_linked_list_cycle;

// #Easy #Top_100_Liked_Questions #Top_Interview_Questions #Hash_Table #Two_Pointers #Linked_List
// #Data_Structure_I_Day_7_Linked_List #Udemy_Linked_List #Big_O_Time_O(N)_Space_O(1)
// #2024_11_15_Time_0_ms_(100.00%)_Space_44.3_MB_(52.46%)

import com_github_leetcode.ListNode;

/*
 * 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 fast = head.next;
        ListNode slow = head;
        while (fast != null && fast.next != null) {
            if (fast == slow) {
                return true;
            }
            fast = fast.next.next;
            slow = slow.next;
        }
        return false;
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy