File tree Expand file tree Collapse file tree
Basics/Data Structure/Stack-Reverser Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ package Stack ;
2+
3+ import java .util .Scanner ;
4+
5+ public class Reverser {
6+ private String input ,output ;
7+
8+ Reverser (String input ){
9+ this .input = input ;
10+ output = "" ;
11+ }
12+
13+ public String reverse (){
14+ StackX stack = new StackX (input .length ());
15+
16+ for (char letter : input .toCharArray ()) {
17+ stack .push (letter );
18+ }
19+
20+
21+
22+ while (!stack .isEmpty ()) {
23+ output += stack .pop ();
24+
25+ }
26+
27+ return output ;
28+ }
29+
30+ public static void main (String [] args ) {
31+ Scanner sc = new Scanner (System .in );
32+ System .out .print ("Enter any text : " );
33+ String str = sc .nextLine ();
34+ Reverser obj = new Reverser (str );
35+ System .out .println ("Reversed :" + obj .reverse ());
36+ sc .close ();
37+ }
38+ }
Original file line number Diff line number Diff line change 1+ package Stack ;
2+
3+ public class StackX {
4+ private char [] data ; //stack array
5+ private int top ; //top of the stack
6+ private int size ; //size of stack array
7+
8+ public StackX (int size ){
9+ this .size = size ;
10+ data = new char [size ];
11+ top = -1 ;
12+ }
13+
14+ //push method
15+ public boolean push (char element ){
16+ if (top < size - 1 ) {
17+ data [++top ] = element ;
18+ return true ;
19+ }
20+
21+ return false ;
22+
23+ }
24+
25+ public char pop (){
26+ if (top != -1 ) {
27+ return data [top --];
28+ }
29+
30+ return ' ' ;
31+ }
32+
33+ public char peek (){
34+ if (top != -1 ) {
35+ return data [top ];
36+ }
37+
38+ return ' ' ;
39+ }
40+
41+ public boolean isFull (){
42+ if (top == size - 1 ) {
43+ return true ;
44+ }
45+
46+ return false ;
47+ }
48+
49+ public boolean isEmpty (){
50+ if (top == -1 ) {
51+ return true ;
52+ }
53+
54+ return false ;
55+ }
56+ }
You can’t perform that action at this time.
0 commit comments