forked from knaxus/problem-solving-javascript
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
38 lines (35 loc) · 836 Bytes
/
index.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
/**
* Sort a stack with the help of a temporary stack.
* Input:[1,10,21,3,9,-11,32]
* Output:[32,21,10,9,3,1,-11]
* Time Complexity:O(N^2)
*/
const Stack = require('../index');
function sortStack(stack) {
const tempStack = new Stack();
while (!stack.isEmpty()) {
// pop the first element from stack
const temp = stack.pop();
// for ascending order (tempStack.peek() < temp)
while (!tempStack.isEmpty() && tempStack.peek() > temp) {
stack.push(tempStack.pop());
}
// push the first element(temp) onto tempStack if tempStack.peek()<temp
tempStack.push(temp);
}
return tempStack;
}
module.exports = sortStack;
/*
const s = new Stack();
s.push(1);
s.push(10);
s.push(21);
s.push(3);
s.push(9);
s.push(-11);
s.push(32);
console.log(s.data);
const s1 = sortStack(s);
console.log(s1.data);
*/