This post is completed by 2 users

  • 0
Add to List
Beginner

323. 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.

Code:


Output:

Original String: tutorial horizon
Reverse String: noziroh lairotut