Steps : 1) Declare an empty stack.
2) put the string elements in a character array.
3) Push every single character of the array into the stack.
4) Pop character one by one from the stack & add the removed character in an empty string.
import java.util.Scanner;
import java.util.Stack;
public class MyStack {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String string = scanner.nextLine();
String output = "";
Stack stack = new Stack();
char[] array = string.toCharArray();
for (char c : array) {
stack.push(c);
}
for (int i = 0; i < array.length; i++){
char c = (char) stack.pop();
output += c;
}
System.out.println("Reversed string : " + output);
}
}
0 comments:
Post a Comment