-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
Copy pathstack_with_array.js
62 lines (43 loc) · 1.3 KB
/
stack_with_array.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
class MyStack {
constructor() {
this.array = []; // Array is used to implement stack
}
// List of main functions of stack data structure
push(value) {
// push an element into the array
this.array.push(value);
}
pop() {
// Underflow if stack is empty
if (this.isEmpty()) {
return "Underflow";
}
return this.array.pop(); // return top most element from the stack and removes the same element
}
peek() {
return this.array[this.array.length - 1]; // return top most element from the stack without removing the element
}
// List of helper functions
isEmpty() {
return this.array.length === 0; // return true if stack is empty
}
printStack() {
let data = "";
for (let i = 0; i < this.array.length; i++)
data += this.array[i] + " ";
return data;
}
}
function useStack() {
let myStack = new MyStack();
console.log(myStack.isEmpty()); // false
console.log(myStack.pop()); // Underflow
myStack.push(1);
myStack.push(2);
myStack.push(3);
console.log(myStack.printStack()); // 1 2 3
console.log(myStack.peek()); // 3
console.log(myStack.pop()); // 3
console.log(myStack.printStack()); // 1 2
}
useStack();