Skip to content

Commit dbeeda6

Browse files
committed
linked list cycle
1 parent 5f7b247 commit dbeeda6

File tree

1 file changed

+36
-0
lines changed

1 file changed

+36
-0
lines changed

linked-list-cycle/eunhwa99.java

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
2+
class ListNode {
3+
4+
int val;
5+
ListNode next;
6+
7+
ListNode(int x) {
8+
val = x;
9+
next = null;
10+
}
11+
}
12+
13+
public class Solution {
14+
15+
// Floyd's Tortoise and Hare Algorithm
16+
// TC: O(N)
17+
// SC: O(1)
18+
public boolean hasCycle(ListNode head) {
19+
if (head == null || head.next == null) {
20+
return false;
21+
}
22+
23+
ListNode slow = head;
24+
ListNode fast = head;
25+
26+
while (fast != null && fast.next != null) {
27+
slow = slow.next;
28+
fast = fast.next.next;
29+
30+
if (slow == fast) {
31+
return true;
32+
}
33+
}
34+
return false;
35+
}
36+
}

0 commit comments

Comments
 (0)