File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ Live Demo
2+ import java .io .IOException ;
3+
4+ public class StringReverserThroughStack {
5+ private String input ;
6+ private String output ;
7+ public StringReverserThroughStack (String in ) {
8+ input = in ;
9+ }
10+ public String doRev () {
11+ int stackSize = input .length ();
12+ Stack theStack = new Stack (stackSize );
13+
14+ for (int i = 0 ; i < input .length (); i ++) {
15+ char ch = input .charAt (i );
16+ theStack .push (ch );
17+ }
18+ output = "" ;
19+ while (!theStack .isEmpty ()) {
20+ char ch = theStack .pop ();
21+ output = output + ch ;
22+ }
23+ return output ;
24+ }
25+ public static void main (String [] args ) throws IOException {
26+ String input = "Java Source and Support" ;
27+ String output ;
28+ StringReverserThroughStack theReverser =
29+ new StringReverserThroughStack (input );
30+ output = theReverser .doRev ();
31+ System .out .println ("Reversed: " + output );
32+ }
33+ class Stack {
34+ private int maxSize ;
35+ private char [] stackArray ;
36+ private int top ;
37+
38+ public Stack (int max ) {
39+ maxSize = max ;
40+ stackArray = new char [maxSize ];
41+ top = -1 ;
42+ }
43+ public void push (char j ) {
44+ stackArray [++top ] = j ;
45+ }
46+ public char pop () {
47+ return stackArray [top --];
48+ }
49+ public char peek () {
50+ return stackArray [top ];
51+ }
52+ public boolean isEmpty () {
53+ return (top == -1 );
54+ }
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments