- Notifications
You must be signed in to change notification settings - Fork 88
Expand file tree
/
Copy pathStackSorting.java
More file actions
Latest commit
51 lines (45 loc) · 1.35 KB
/
Copy pathStackSorting.java
File metadata and controls
51 lines (45 loc) · 1.35 KB
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
packagestackqueues.stacksorting;
importjava.util.Stack;
/**
* Sort a stack using only one additional stack and no other data structure.
* Created by techpanja
* Created on 1/19/14 7:54 PM.
*/
publicclassStackSorting {
privateStackSorting() {
}
publicstaticStack<Integer> sortStack(Stack<Integer> inputStack) {
if (inputStack.empty()) {
returnnewStack<>();
}
Stack<Integer> tempStack = newStack<>();
while (!inputStack.empty()) {
inttemp = inputStack.pop();
if (tempStack.empty()) {
tempStack.push(temp);
} else {
while (!tempStack.empty() && tempStack.peek() > temp) {
inputStack.push(tempStack.pop());
}
tempStack.push(temp);
}
}
returntempStack;
}
publicstaticvoidmain(String[] args) {
Stack<Integer> inputStack = newStack<>();
inputStack.push(5);
inputStack.push(4);
inputStack.push(7);
inputStack.push(7);
inputStack.push(6);
inputStack.push(9);
inputStack.push(9);
inputStack.push(1);
inputStack.push(11);
Stack<Integer> stack = sortStack(inputStack);
while (!stack.empty()) {
System.out.println(stack.pop());
}
}
}