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 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
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Add two numbers in Scala - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Goal Parser Interpretation LeetCode Solution - The Coding Shala

New Year Chaos Solution - The Coding Shala