Skip to content

Commit 7ccb856

Browse files
author
rpanjrath
committed
Stacks: Sort a stack using only one additional stack and no other data structure.
1 parent 2614f35 commit 7ccb856

2 files changed

Lines changed: 55 additions & 1 deletion

File tree

README.md

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -157,9 +157,12 @@ Sorting
157157

158158
Stack/Queues
159159
------------
160-
1. Implement a queue using stack.
160+
1. Implement a queue using stack.
161161
Link: https://github.com/techpanja/interviewproblems/blob/master/src/stackqueues/queueusingstack/QueueUsingStack.java
162162

163+
2. Sort a stack using only one additional stack and no other data structure.
164+
Link:
165+
163166
Strings
164167
-------
165168
1. Check string palindrome.
Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package stackqueues.stacksorting;
2+
3+
import java.util.Stack;
4+
5+
/**
6+
* Sort a stack using only one additional stack and no other data structure.
7+
* Created by techpanja
8+
* Created on 1/19/14 7:54 PM.
9+
*/
10+
public class StackSorting {
11+
12+
private StackSorting() {
13+
14+
}
15+
16+
public static Stack<Integer> sortStack(Stack<Integer> inputStack) {
17+
if (inputStack.empty()) {
18+
return new Stack<>();
19+
}
20+
Stack<Integer> tempStack = new Stack<>();
21+
while (!inputStack.empty()) {
22+
int temp = inputStack.pop();
23+
if (tempStack.empty()) {
24+
tempStack.push(temp);
25+
} else {
26+
while (!tempStack.empty() && tempStack.peek() > temp) {
27+
inputStack.push(tempStack.pop());
28+
}
29+
tempStack.push(temp);
30+
}
31+
}
32+
return tempStack;
33+
}
34+
35+
public static void main(String[] args) {
36+
Stack<Integer> inputStack = new Stack<>();
37+
inputStack.push(5);
38+
inputStack.push(4);
39+
inputStack.push(7);
40+
inputStack.push(7);
41+
inputStack.push(6);
42+
inputStack.push(9);
43+
inputStack.push(9);
44+
inputStack.push(1);
45+
inputStack.push(11);
46+
Stack<Integer> stack = sortStack(inputStack);
47+
while (!stack.empty()) {
48+
System.out.println(stack.pop());
49+
}
50+
}
51+
}

0 commit comments

Comments
 (0)