-
-
Notifications
You must be signed in to change notification settings - Fork 81
/
Copy pathstack_class.js
88 lines (68 loc) · 1.32 KB
/
stack_class.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
80
81
82
83
84
85
86
87
88
class Stack {
constructor() {
this.items = [];
}
push(item) {
this.items.push(item);
}
pop() {
return this.items.pop();
}
top() {
return this.items[this.items.length - 1];
}
isEmpty() {
return this.size() === 0;
}
size() {
return this.items.length;
}
}
// testing
const stack = new Stack();
console.log(stack.isEmpty());
stack.push(1);
console.log(stack.items);
stack.push(2);
console.log(stack.items);
stack.push(3);
console.log(stack.items);
stack.push(4);
console.log(stack.items);
stack.push(5);
console.log(stack.items);
console.log(stack.isEmpty());
console.log(stack.top());
stack.pop();
console.log(stack.items);
stack.pop();
console.log(stack.items);
stack.pop();
console.log(stack.items);
stack.pop();
console.log(stack.items);
console.log(stack.isEmpty());
stack.pop();
console.log(stack.items);
console.log(stack.isEmpty());
console.log(stack.top());
// Reversing a list with the stack data structure
function reverse(list) {
const stack = new Stack();
for (item of list) {
stack.push(item);
}
const reversedList = [];
while (!stack.isEmpty()) {
reversedList.push(stack.pop());
}
return reversedList;
}
const reversedBooks = reverse([
'Harry Potter',
'Atomic Habits',
'Leonardo da Vinci',
'Sapiens',
'Peak',
]);
console.log(reversedBooks);