Java Program to Reverse a String using Stack - The Coding Shala
Home >> Java Programs >> Reverse a String using Stack Hey there, welcome back to another post. In this post, we will learn how to reverse a string using a stack in Java. Java Program to Reverse a String using Stack As we know, Stack data structure follows last in the first out (LIFO), so by using stack we can reverse a given string. For example: Input: hello output: olleh After storing into stack Stack -> o l l e h Now print stack -> olleh Java Program: import java.util.Scanner; import java.util.Stack; /** * https://www.thecodingshala.com/ */ public class Main { public static String doReverse(String str) { Stack<Character> stack = new Stack<>(); // push all characters into stack for ( int i = 0; i < str.length(); i++) { stack.push(str.charAt(i)); } // pop characters from stack and build s...