This post is completed by 2 users

  • 0
Add to List
Beginner

323. How to Reverse Text: Stack Method for String Reversal

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.

Output:

Original String: tutorial horizon
Reverse String: noziroh lairotut