File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments