-
Notifications
You must be signed in to change notification settings - Fork 0
/
Stack.js
49 lines (43 loc) · 1.62 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
44
45
46
47
48
49
// ****************************************************************************
class Stack {
// ------------------------------------------------------------------------
constructor() {
this.items = [];
}
// ------------------------------------------------------------------------
push(item) {
this.items.push(item);
return true;
}
// ------------------------------------------------------------------------
pop() {
// if (this.items.length === 0) return false;
return this.items.pop();
}
// ------------------------------------------------------------------------
peek() {
if (this.isEmpty()) return null;
else return this.items[this.items.length - 1];
}
// ------------------------------------------------------------------------
isEmpty() {
return this.items.length === 0;
}
// ------------------------------------------------------------------------
printStack() {
let items_str = "";
for (let i = 0; i < this.items.length; i++) items_str += this.items[i];
return items_str;
}
}
// ****************************************************************************
const new_stack = new Stack();
console.log("Is empty ", new_stack.isEmpty());
console.log("Pop ", new_stack.pop());
console.log("Push 10 ", new_stack.push(10));
console.log("Push 20 ", new_stack.push(20));
console.log("Push 20 ", new_stack.push(20));
console.log("Print Stack ", new_stack.printStack());
console.log("Peek ", new_stack.peek());
console.log("Pop ", new_stack.pop());
console.log("Print Stack ", new_stack.printStack());