File tree Expand file tree Collapse file tree 2 files changed +62
-0
lines changed
java/Fast and Slow Pointers Expand file tree Collapse file tree 2 files changed +62
-0
lines changed Original file line number Diff line number Diff line change
1
+ import DS .ListNode ;
2
+
3
+ /*
4
+ // Definition of ListNode:
5
+ class ListNode {
6
+ public int val;
7
+ public ListNode next;
8
+ public ListNode(int val) { this.val = val; }
9
+ public ListNode(int val, ListNode next) {
10
+ this(val);
11
+ this.next = next;
12
+ }
13
+ }
14
+ */
15
+
16
+
17
+ public class LinkedListLoop {
18
+ public boolean linkedListLoop (ListNode head ) {
19
+ ListNode slow , fast ;
20
+ slow = fast = head ;
21
+ // Check both 'fast' and 'fast.next' to avoid null pointer
22
+ // exceptions when we perform 'fast.next' and 'fast.next.next'.
23
+ while (fast != null && fast .next != null ) {
24
+ slow = slow .next ;
25
+ fast = fast .next .next ;
26
+ if (fast == slow ) return true ;
27
+ }
28
+ return false ;
29
+ }
30
+ }
Original file line number Diff line number Diff line change
1
+ import java .util .HashSet ;
2
+ import java .util .Set ;
3
+
4
+ import DS .ListNode ;
5
+
6
+ /*
7
+ // Definition of ListNode:
8
+ class ListNode {
9
+ public int val;
10
+ public ListNode next;
11
+ public ListNode(int val) { this.val = val; }
12
+ public ListNode(int val, ListNode next) {
13
+ this(val);
14
+ this.next = next;
15
+ }
16
+ }
17
+ */
18
+
19
+
20
+ public class LinkedListLoopNaive {
21
+ public boolean linkedListLoopNaive (ListNode head ) {
22
+ Set <ListNode > visited = new HashSet <>();
23
+ ListNode curr = head ;
24
+ while (curr != null ) {
25
+ // Cycle detected if the current node has already been visited.
26
+ if (visited .contains (curr )) return true ;
27
+ visited .add (curr );
28
+ curr = curr .next ;
29
+ }
30
+ return false ;
31
+ }
32
+ }
You can’t perform that action at this time.
0 commit comments