File tree 1 file changed +44
-0
lines changed
src/main/java/com/ctci/stacksandqueues
1 file changed +44
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments