Java Program to Reverse a String using Stack

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

Reverse a string using stack

Java Program to Reverse a String using Stack

We have discussed an algorithm to let’s write a java code to implement this algorithm.

 

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.

Practice questions on stack

Tagged , , . Bookmark the permalink.

About WebRewrite

I am technology lover who loves to keep updated with latest technology. My interest field is Web Development.