forked from josegarrera/repaso-M1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
DS.js
79 lines (70 loc) · 1.54 KB
/
DS.js
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
71
72
73
74
75
76
77
78
79
// Creamos la clase Binary Search Tree
class BinarySearchTree {
constructor(value) {
this.value = value;
this.left = null;
this.right = null;
}
// Creamos el metodo insert
insert(value) {
// Si el arbol esta vacio lo inicializa
if (!this.value) return (this.value = value);
(function add(value, current) {
// Si el valor es mayor que el valor actual
if (current.value < value) {
current.right
? add(value, current.right)
: (current.right = new BinarySearchTree(value));
return;
}
// Si el valor es menor o igual
current.left
? add(value, current.left)
: (current.left = new BinarySearchTree(value));
})(value, this);
// IIFE
}
}
// Creamos la clase LinkedList
class LinkedList {
constructor() {
this.head = null;
}
add(value) {
const newNode = new Node(value);
if (!this.head) return (this.head = newNode);
let tail = this.head;
while (tail.next) {
tail = tail.next;
}
tail.next = newNode;
}
remove() {
if (!this.head) return null;
if (!this.head.next) {
const aux = this.head;
this.head = null;
return aux;
}
let tail = this.head.next;
let prev = this.head;
while (tail.next) {
prev = tail;
tail = tail.next;
}
prev.next = null;
return tail.value;
}
}
// Creamos la clase Node
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
module.exports = {
BinarySearchTree,
LinkedList,
Node,
};