File tree Expand file tree Collapse file tree 1 file changed +45
-0
lines changed
Expand file tree Collapse file tree 1 file changed +45
-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+ public class Solution {
13+ public boolean hasCycle (ListNode head ) {
14+
15+ if (head == null ){
16+ return false ;
17+ }
18+
19+ ListNode slowPtr = head ;
20+ ListNode fastPtr = head ;
21+
22+ /** Approach
23+
24+ // 1. if no cycle exists AND
25+ // a. if there are even number of nodes then fast pointer will be pointing to null.
26+ // b. else there are odd number of nodes then fast pointer will be pointing to last node.
27+
28+ // 2. if slow pointer meet fast pointer that interprets there exists a loop
29+ */
30+
31+ while (fastPtr != null && fastPtr .next != null ) {
32+
33+ // move slow pointer one node at a time
34+ slowPtr = slowPtr .next ;
35+
36+ // move fast pointer two nodes at a time
37+ fastPtr = fastPtr .next .next ;
38+
39+ if (slowPtr == fastPtr )
40+ return true ;
41+ }
42+
43+ return false ;
44+ }
45+ }
You can’t perform that action at this time.
0 commit comments