Java Program to Reverse a String using Stack - The Coding Shala
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 string StringBuilder sb = new StringBuilder(); while (!stack.isEmpty()) { sb.append(stack.pop()); } return sb.toString(); } public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter a String"); String str = sc.next(); String reverse = doReverse(str); System.out.println("Reverse string is: " + reverse); } }
Output:
Enter a String thecodingshala Reverse string is: alahsgnidoceht
Other Posts You May Like
- Java Program to Reverse a String
- Java Program to Reverse a String using Recursion
- Java Program to Convert Binary to Decimal
- Java Program to Convert Decimal to Binary
- Java Program to Check Armstrong Number
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.
Comments
Post a Comment