-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstack.js
43 lines (41 loc) · 1.11 KB
/
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
console.log('---------Stack start---------');
class Stack {
#storage;
constructor() {
this.#storage = {};
this.length = 0;
}
push(value) {
this.#storage[this.length++] = value;
}
pop() {
if (this.length > 0) {
const value = this.#storage[this.length - 1];
delete this.#storage[this.length - 1];
this.length--;
return value;
} else return undefined;
}
peek() {
return this.#storage[this.length - 1];
}
}
let s = new Stack();
s.push(1);
s.push(2);
s.push(3);
s.push(4);
s.push(5);
console.log(s);
console.log('Return 5 ' + s.peek());
console.log('Return 5 ' + s.pop());
console.log('Return length 4 ' + s.length);
console.log('Return 4 ' + s.pop());
console.log('Return 3 ' + s.pop());
console.log('Return 2 ' + s.pop());
console.log('Return 1 ' + s.pop());
console.log('Return undefined ' + s.pop()); // undefined
console.log('Return undefined' + s.pop()); // undefined
console.log('Return undefined ' + s.pop()); // undefined
console.log('Return 0 ' + s.length); // undefined
console.log('----------stack end--------------');