Skip to content

Commit 41fef14

Browse files
SumeetHaryaniTheSTL
authored andcommitted
Added sort a stack problem and solution. (knaxus#85)
* add solution to sort a stack problem * update README.md * add time compexity
1 parent 28e1e01 commit 41fef14

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

README.md

+2
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,8 @@ Collection of interview questions with Unit Tests. Problems includes Data Struct
2929
- [Postfix Expression Evaluation](src/_DataStructures_/Stack/postfix-expression-evaluation)
3030
- [Remove Consecutive Repeated Digits](src/_DataStructures_/Stack/remove-consecutive-repeated-digits)
3131
- [Implement 2 Stacks using Single Array](src/_DataStructures_/Stack/2-stacks-using1-array)
32+
- [Sort a Stack](src/_DataStructures_/Stack/sort-a-stack)
33+
3234

3335
- [Queue](src/_DataStructures_/Queue)
3436

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
/**
2+
* Sort a stack with the help of a temporary stack.
3+
* Input:[1,10,21,3,9,-11,32]
4+
* Output:[32,21,10,9,3,1,-11]
5+
* Time Complexity:O(N^2)
6+
*/
7+
const Stack = require('../index');
8+
9+
function sortStack(stack) {
10+
const tempStack = new Stack();
11+
while (!stack.isEmpty()) {
12+
//pop the first element from stack
13+
let temp = stack.pop();
14+
//for ascending order (tempStack.peek() < temp)
15+
while (!tempStack.isEmpty() && tempStack.peek() > temp) {
16+
stack.push(tempStack.pop());
17+
}
18+
//push the first element(temp) onto tempStack if tempStack.peek()<temp
19+
tempStack.push(temp);
20+
}
21+
return tempStack;
22+
}
23+
/*
24+
const s = new Stack();
25+
26+
s.push(1);
27+
s.push(10);
28+
s.push(21);
29+
s.push(3);
30+
s.push(9);
31+
s.push(-11);
32+
s.push(32);
33+
console.log(s.data);
34+
const s1 = sortStack(s);
35+
console.log(s1.data);
36+
*/

0 commit comments

Comments
 (0)