-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathlinkedListCycles.js
More file actions
50 lines (42 loc) · 1.15 KB
/
linkedListCycles.js
File metadata and controls
50 lines (42 loc) · 1.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/*
* Assignment: Write a function that returns true if a linked list
* contains a cycle, or false if it terminates somewhere
*
* Explanation:
*
* Generally, we assume that a linked list will terminate
in a null next pointer, as follows:
*
* A -> B -> C -> D -> E -> null
*
* A 'cycle' in a linked list is when traversing the list would
* result in visiting the same nodes over and over
* This is caused by pointing a node in the list to another node
* that already appeared earlier in the list. Example:
*
* A -> B -> C
* ^ |
* | v
* E <- D
*
* Example code:
*
* var nodeA = Node('A');
* var nodeB = nodeA.next = Node('B');
* var nodeC = nodeB.next = Node('C');
* var nodeD = nodeC.next = Node('D');
* var nodeE = nodeD.next = Node('E');
* hasCycle(nodeA); // => false
* nodeE.next = nodeB;
* hasCycle(nodeA); // => true
*
* Constraint 1: Do this in linear time
* Constraint 2: Do this in constant space
* Constraint 3: Do not mutate the original nodes in any way
*/
var Node = function(value) {
return { value: value, next: null };
};
var hasCycle = function(linkedList) {
// TODO: implement me!
};