/
stack.js
115 lines (83 loc) · 2.14 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
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
class Stack
{
constructor()
{
this.items = [];
this.count = 0;
}
// Adds element to the top of the stack
push(element) // Time Complexity O(1)
{
this.items[this.count] = element;
console.log(`${element} added to ${this.count}`)
this.count += 1;
return this.count - 1;
}
// Returns and removes top element in stack
// Returns undefined if stack is empty
pop() // Time Complexity O(1)
{
if(this.count === 0) return undefined;
let deleteItm = this.items[this.count - 1];
console.log(`${deleteItm} removed`)
this.count--;
return deleteItm;
}
// Checks top element in stack
peek()
{
console.log(`Top element in stack ${this.items[this.count - 1]}`);
return this.items[this.count - 1];
}
// Checks if stack is empty
isEmpty()
{
console.log(this.count === 0 ? 'Stack is empty' : 'Stack is NOT empty');
return this.count === 0;
}
// Stacks size
size()
{
console.log(`Stack size ${this.count}`)
return this.count;
}
print()
{
let str = '';
if(this.count != 0)
{
for(let i = 0; i< this.count; i++)
{
str += this.items[i] + ' ';
}
}
else{str = '[EMPTY]'}
return str;
}
// Clears stack
clear()
{
this.items = [];
this.count = 0;
console.log('Stack cleared...');
return this.items;
}
}
// LIFO Principle (LIFO: Last in First Out)
// Space Complexity O(n)
// The lines below are not part of the data structure
/*
const stack = new Stack();
stack.isEmpty();
stack.push(100);
stack.push(200);
stack.peek();
stack.push(300);
console.log('Stack: ' + stack.print())
stack.pop();
stack.size();
console.log('Stack: ' + stack.print())
stack.clear();
stack.size();
console.log('Stack: ' + stack.print())
*/