We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
There was an error while loading. Please reload this page.
1 parent 6ebd1db commit e2977c4Copy full SHA for e2977c4
linked-list-cycle/ekgns33.java
@@ -0,0 +1,35 @@
1
+/**
2
+ * Definition for singly-linked list.
3
+ * class ListNode {
4
+ * int val;
5
+ * ListNode next;
6
+ * ListNode(int x) {
7
+ * val = x;
8
+ * next = null;
9
+ * }
10
11
+ */
12
+
13
+/*
14
+* input : singly linked list and head node
15
+* output : return true if list has cycle
16
+*
17
+* solution : tortoise and hare algorithm
18
+* with two pointer (slow and fast)
19
+* tc : O(n)
20
+* sc : O(1)
21
22
+* */
23
+public class Solution {
24
+ public boolean hasCycle(ListNode head) {
25
+ if(head == null) return false;
26
+ ListNode slow = head;
27
+ ListNode fast = head;
28
+ while(fast.next != null && fast.next.next != null) {
29
+ slow = slow.next;
30
+ fast = fast.next.next;
31
+ if(fast == slow) return true;
32
+ }
33
+ return false;
34
35
+}
0 commit comments