From 2d4ba86cbea382d641515140e468a3e14db55c5c Mon Sep 17 00:00:00 2001 From: Matej Focko Date: Wed, 6 Mar 2024 23:05:20 +0100 Subject: [PATCH] =?UTF-8?q?java:=20add=20=C2=AB141.=20Linked=20List=20Cycl?= =?UTF-8?q?e=C2=BB?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Matej Focko --- java/linked-list-cycle.java | 21 +++++++++++++++++++++ 1 file changed, 21 insertions(+) create mode 100644 java/linked-list-cycle.java diff --git a/java/linked-list-cycle.java b/java/linked-list-cycle.java new file mode 100644 index 0000000..46aca47 --- /dev/null +++ b/java/linked-list-cycle.java @@ -0,0 +1,21 @@ +/** + * 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) { + var x = head; + var y = head; + + while (y != null && y.next != null) { + x = x.next; + y = y.next.next; + + if (x == y) { + return true; + } + } + + return false; + } +}