How to create a stack with a sort method in JavaScript

Here is one way to create a stack with a sort method in JavaScript:

sortStackTry in REPL
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
function Stack() {
this.top = null;
this.size = 0;
}
function Node(data) {
this.data = data;
this.next = null;
}
Stack.prototype.push = function(data) {
const node = new Node(data);
node.next = this.top;
this.top = node;
this.size++;
};
Stack.prototype.pop = function() {
if (this.top === null) return;
const data = this.top.data;
this.top = this.top.next;
this.size = Math.max(0, this.size - 1);
return data;
};
Stack.prototype.peek = function() {
if (!this.top) return;
return this.top.data;
};
Stack.prototype.isEmpty = function() {
return this.size === 0 && !this.top;
};
// Time complexity: O(n^2)
// Space complexity: O(n)
Stack.prototype.sort = function() {
const temp = new Stack();
while (!this.isEmpty()) {
const item = this.pop();
while (!temp.isEmpty() && temp.peek() > item) {
this.push(temp.pop());
}
temp.push(item);
}
while (!temp.isEmpty()) {
this.push(temp.pop());
}
};

Tests can be found at REPL.it