-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStack.js
45 lines (40 loc) · 915 Bytes
/
Stack.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
class Stack {
constructor() {
this.top = null;
this.bottom = null;
this.length = 0;
}
// Nos permite obtener el último elemento en entrar
peek() {
this.top;
}
// Nos permite agregar un elemento a nuestra pila
push(value) {
const newNode = new Node(value);
if (this.length === 0) {
this.top = newNode;
this.bottom = newNode;
} else {
newNode.next = this.top;
this.top = newNode;
}
this.length += 1;
this;
}
// Nos permite eliminar el último elemento
pop() {
if (this.length > 0) {
this.top = this.top.next;
this.length -= 1;
if (this.length === 0) {
this.bottom = null;
}
}
}
};
const stack = new Stack(1);
stack.push(1);
stack.push(2);
stack.push(3);
stack.pop();
console.log(stack.peek());