-
Notifications
You must be signed in to change notification settings - Fork 0
/
stack.js
59 lines (51 loc) · 1.4 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
class Stack {
constructor() {
this._items = new Array();
this._minStack = new Array();
this._tempStack = new Array();
}
get items() {
return this._items;
}
get min() {
return this._minStack[this._minStack.length - 1];
}
pop() {
if (this.isEmpty()) {
throw new Error("Stack is empty.");
}
if (this.min && this.min === this._items[this._items.length - 1]) {
this._minStack.pop();
}
return this._items.pop();
}
push(item) {
if (this.min == null || item < this.min) {
this._minStack.push(item);
}
this._items.push(item);
}
peek() {
if (this.isEmpty()) {
throw new Error("Stack is empty.");
}
return this._items[this._items.length - 1];
}
isEmpty() {
return this._items.length === 0;
}
sort() {
while (this._items.length > 0) {
let currentItem = this._items.pop();
while (this._tempStack.length > 0 &&
this._tempStack[this._tempStack.length - 1] > currentItem) {
this._items.push(this._tempStack.pop());
}
this._tempStack.push(currentItem);
}
while (this._tempStack.length > 0) {
this._items.push(this._tempStack.pop());
}
}
}
module.exports = { Stack };