Write a java program to reverse a string using stack data structure. Given an input string, We have to write a java code to reverse a string using stack.
In my previous tutorial, I have explained java program to reverse a string using recursion.
Before solving this problem, Let’s understand what is a stack data structure.
Stack
A stack is linear data structure in which insertion and deletion operations are allowed only at one end. It is also called LIFO (Last In First Out) data structure. In LIFO, an element which inserted at last is the first element to be deleted.
In Stack, Insertion and Deletion operations are known as push and pop.
Push – To insert an element in a Stack.
Pop – To delete an element from a Stack.
How to Reverse a String using Stack
We can use the property of stack data structure to reverse a string. Here are the algorithm –
First we have to push all the characters of a string in a stack. Once all the characters are pushed the next step is to pop the characters from a stack.
To understand this let’s take an example. Suppose, our input string is java. When we push the characters in a stack first j is pushed followed by a, v, a. After that when we pop the character first a is popped out followed by v, a, j.
Push order : J, a, v, a
Pop order : a, v, a, J
Java Program to Reverse a String using Stack
We have discussed an algorithm to let’s write a java code to implement this algorithm.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
import java.util.Scanner; import java.util.Stack; /** * Java Program to Reverse a String using Stack * Source - https://webrewrite.com * * Input String : Java * * Output String: avaJ */ public class ReverseString { public static void main(String[] args) { //Take input string Scanner in = new Scanner(System.in); System.out.println("Enter a string"); String str = in.nextLine(); //Declare a stack Stack stack = new Stack<>(); /** * Traverse a string and push each character * of a string in a stack. */ for(int i = 0; i < str.length(); i++) { stack.push(str.charAt(i)); } System.out.println("Reverse of a string"); //When stack is not empty, pop each character while(!stack.empty()) { System.out.print(stack.pop()); } } } |
Find next greater element in an array
Video Tutorial To Reverse a String using Stack
Java program to reverse a string using stack video tutorial
If you want to practice more questions on the stack data structure. Here is the playlist which consists of more than 30 questions.