Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
Skip to content

Commit 4ee5b95

Browse files
committed
SortStack: done
1 parent f18aecb commit 4ee5b95

File tree

1 file changed

+44
-0
lines changed

1 file changed

+44
-0
lines changed
Lines changed: 44 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,44 @@
1+
package com.ctci.stacksandqueues;
2+
3+
import java.util.Arrays;
4+
import java.util.Stack;
5+
6+
/**
7+
* @author rampatra
8+
* @since 2019-02-08
9+
*/
10+
public class SortStack {
11+
12+
private static void sortStack(Stack<Integer> stack) {
13+
Stack<Integer> tempStack = new Stack<>();
14+
while (!stack.empty()) {
15+
tempStack.push(stack.pop());
16+
}
17+
while (!tempStack.empty()) {
18+
Integer item = tempStack.pop();
19+
if (stack.empty()) {
20+
stack.push(item);
21+
} else {
22+
while (!stack.empty() && item > stack.peek()) {
23+
tempStack.push(stack.pop());
24+
}
25+
stack.push(item);
26+
}
27+
}
28+
}
29+
30+
private static void printStack(Stack<Integer> stack) {
31+
System.out.println(Arrays.toString(stack.toArray()));
32+
}
33+
34+
public static void main(String[] args) {
35+
Stack<Integer> unsortedStack = new Stack<>();
36+
unsortedStack.push(2);
37+
unsortedStack.push(5);
38+
unsortedStack.push(1);
39+
unsortedStack.push(3);
40+
printStack(unsortedStack);
41+
sortStack(unsortedStack);
42+
printStack(unsortedStack);
43+
}
44+
}

0 commit comments

Comments
 (0)