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 Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala