File tree Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Expand file tree Collapse file tree 1 file changed +47
-0
lines changed Original file line number Diff line number Diff line change
1
+ /**
2
+ * Hackerrank
3
+ * A linked list is said to contain a cycle if any node is visited more than
4
+ * once while traversing the list. Complete the function provided for you in
5
+ * your editor. It has one parameter: a pointer to a Node object named that
6
+ * points to the head of a linked list. Your function must return a boolean
7
+ * denoting whether or not there is a cycle in the list. If there is a cycle,
8
+ * return true; otherwise, return false.
9
+ *
10
+ * Constraints:
11
+ * 1. 0 <= list size <= 1000
12
+ *
13
+ * This solution got 5 points
14
+ * Problem link: http://hr.gs/ffddcc
15
+ */
16
+
17
+ /*
18
+ * For your reference:
19
+ *
20
+ * SinglyLinkedListNode {
21
+ * int data;
22
+ * SinglyLinkedListNode next;
23
+ * }
24
+ *
25
+ */
26
+
27
+ /**
28
+ * @param {SinglyLinkedListNode } head The root of the linked list
29
+ * @return {boolean } If there's a cycle in the linked list
30
+ */
31
+ function hasCycle ( head ) {
32
+ // Edge case
33
+ if ( ! head ) {
34
+ return false ;
35
+ }
36
+ const visited = new Set ( ) ;
37
+ let node = head ;
38
+ while ( node ) {
39
+ if ( visited . has ( node ) ) {
40
+ return true ;
41
+ } else {
42
+ visited . add ( node ) ;
43
+ }
44
+ node = node . next ;
45
+ }
46
+ return false ;
47
+ }
You can’t perform that action at this time.
0 commit comments