File tree Expand file tree Collapse file tree 1 file changed +49
-0
lines changed
src/main/java/com/thealgorithms/strings Expand file tree Collapse file tree 1 file changed +49
-0
lines changed Original file line number Diff line number Diff line change 1+ package com .thealgorithms .strings ;
2+
3+ import java .util .Scanner ;
4+ import java .util .Stack ;
5+
6+ public class ReverseStringUsingStack {
7+
8+ /**
9+ * Main method to take user input and print the reversed string.
10+ */
11+ public static void main (String [] args ) {
12+
13+ // Create a Scanner object to read input from the user
14+ Scanner sc = new Scanner (System .in );
15+ System .out .print ("Enter the String to reverse : " );
16+ String str = sc .nextLine ();
17+
18+ // Call the reverse method and print the reversed string
19+ System .out .println ("Reversed String : " + reverse (str ));
20+ sc .close ();
21+
22+ }
23+
24+ /**
25+ * Reverses a string using a stack.
26+ *
27+ * @param str The input string to reverse
28+ * @return The reversed string
29+ */
30+ public static String reverse (String str ) {
31+ // StringBuilder to build the reversed string
32+ StringBuilder sb = new StringBuilder ();
33+ // Stack to hold the characters of the string
34+ Stack <Character > st = new Stack <>();
35+
36+ // Push each character of the string onto the stack
37+ for (int i = 0 ; i < str .length (); i ++) {
38+ st .push (str .charAt (i ));
39+ }
40+
41+ // Pop characters from the stack and append to StringBuilder
42+ while (!st .empty ()) {
43+ sb .append (st .pop ());
44+ }
45+ // Convert StringBuilder to String and return
46+ String rev = sb .toString ();
47+ return rev ;
48+ }
49+ }
You can’t perform that action at this time.
0 commit comments