You all are aware of Stack, a data structure, having two fundamental operations: push and pop. In stacks, items are removed in the reverse order from that in which they are added. The push operation is responsible for adding the element and pop for removing. Here we are going to reverse the string using these operations.
Here is the code:
import java.util.*;
class StackReverseString {
public static String revString(String str) {
Stack stack = new Stack();
for (int i = 0; i < str.length(); i++) {
stack.push(str.substring(i, i + 1));
}
String strrev = "";
while (!stack.isEmpty()) {
strrev += stack.pop();
}
return strrev;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.println("Enter a string: ");
String str = scanner.nextLine();
String reversedString = StackReverseString.revString(str);
System.out.println(reversedString);
}
}
Output:
| Enter a String: Hello World dlroW olleH |
If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.
Ask your questions, our development team will try to give answers to your questions.