Reverse the given String using Stack

Objective: Given a String, write a java program to reverse the string using Stack

Example:

Input: “tutorial horizon”
Output: “noziroh lairotut”

Recommended: Please read Stack Data Structure before continue to read.

Approach:

  • Initialize a StringBuffer, this will be our output.
  • Initialize a Stack.
  • Traverse through string, one character at a time and keep adding it to Stack.
  • While stack is not empty, keep popping out the characters from stack and add it to the output StringBuffer.
  • Print the output.

Java Code:



Output:

Original String: tutorial horizon
Reverse String: noziroh lairotut

__________________________________________________
Top Companies Interview Questions..-

Google Microsoft Amazon Facebook more..

If you find anything incorrect or you feel that there is any better approach to solve the above problem, please write comment.
__________________________________________________

%d bloggers like this: