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

g0101_0200.s0141_linked_list_cycle.Solution Maven / Gradle / Ivy

There is a newer version: 1.37
Show 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 #2022_02_23_Time_0_ms_(100.00%)_Space_46.5_MB_(9.38%)

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