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:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Stack; | |
public class ReverseStringStack { | |
static void reverse(String input){ | |
StringBuffer output = new StringBuffer(); | |
if(input==null || input.isEmpty()) | |
return; | |
Stack<Character> stack = new Stack<>(); | |
for (int i = 0; i <input.length() ; i++) { | |
stack.add(input.charAt(i)); | |
} | |
//traverse through stack, pop the characters and add it to StringBUffer | |
while (stack.empty()==false){ | |
output.append(stack.pop()); | |
} | |
System.out.println("Original String: " + input); | |
System.out.println("Reverse String: " + output); | |
} | |
public static void main(String[] args) { | |
String input = "tutorial horizon"; | |
reverse(input); | |
} | |
} |
Output:
Original String: tutorial horizon Reverse String: noziroh lairotut