File tree Expand file tree Collapse file tree
src/stackqueues/stacksorting Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -157,9 +157,12 @@ Sorting
157157
158158Stack/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+
163166Strings
164167-------
1651681 . Check string palindrome.
Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments