forked from CodeToExpress/dailycodebase
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathstackReverse.js
81 lines (69 loc) · 1.65 KB
/
stackReverse.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
/**
* Reverse the stack
* @author MadhavBahl
* @date 12/02/2019
*/
class Stack {
constructor (limit) {
this.myStack = [];
this.tempStack = [];
this.capacity = limit;
}
// Implement isFull() method
isFull () {
if (this.myStack.length === this.capacity) return true;
return false;
}
// Implement isEmpty() method
isEmpty () {
if (this.myStack.length === 0) return true;
return false;
}
// Implement push(x) method
push (element) {
if (this.isFull()) return false;
this.myStack.push(element);
return true;
}
// Implement pop() method
pop () {
if (this.isEmpty()) return -1;
return this.myStack.pop();
}
// Implement the peek() function
peek () {
return this.myStack[this.myStack.length - 1];
}
// Implement reverse() method
reverse () {
this.tempStack = [];
while (!this.isEmpty()) {
let top = this.pop ();
console.log ('temp = ', top);
this.tempStack.push (top);
}
this.myStack = this.tempStack;
}
// Implement displayAll() method
displayAll () {
console.log ('/* ==== My Stack ==== */');
console.log ('Top');
this.tempStack = this.myStack;
while (!this.isEmpty())
console.log (this.pop());
this.myStack = this.tempStack;
console.log ('Bottom');
}
}
const stk = new Stack (10);
stk.push (1);
stk.push (2);
stk.push (19);
stk.push (12);
stk.push (16);
stk.push (4);
stk.push (25);
stk.push (5);
stk.displayAll ();
stk.reverse ();
stk.displayAll ();