-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathproblem_006.js
More file actions
70 lines (62 loc) Β· 1.42 KB
/
problem_006.js
File metadata and controls
70 lines (62 loc) Β· 1.42 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// This code will not run because `get_pointer` and `dereference_pointer` are given in the problem. This assumes they will work as intended.
class ListNode {
/**
* Initialize ListNode
* @param {*} val
*/
constructor(val) {
this.val = val;
this.both = null;
}
}
class XORListNode {
/**
* Initialize XOR Linked List
*/
constructor() {
this.root = null;
this.tail = null
}
/**
* Adds an element to the end of the linked list
* @param {*} element
*/
add(element) {
const node = new ListNode(element);
if(this.root == null && this.tails == null) {
this.root = node;
this.tail = node;
} else {
node.both = get_pointer(this.tail);
this.tail.both ^= get_pointer(node);
this.tail = node;
}
}
/**
* Returns the node at index of this XOR Linked List
* @param {number} index
* @return {ListNode}
*/
get(index) {
// Base cases
if(this.root === null) return null;
if(index === 0) return this.root;
var curr = get_pointer(this.root);
var prev = null;
var i = 0;
// Continue until at the same index
// The XOR ListNode defined as:
// prev ^ next = curr.
// To traverse:
// prev ^ curr = next.
while(curr !== null) {
if(i === index) break;
var next = prev ^ curr;
prev = curr;
curr = next;
i++;
}
if (i !== index) return null;
return dereference_pointer(curr);
}
}