java: add «141. Linked List Cycle»

Signed-off-by: Matej Focko <mfocko@redhat.com>
This commit is contained in:
Matej Focko 2024-03-06 23:05:20 +01:00
parent b9f735f1e8
commit 2d4ba86cbe
Signed by: mfocko
GPG key ID: 7C47D46246790496

View file

@ -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;
}
}