Reverse the given string using stack.
Implementation: Iterate the string till the end of the length and put each character into the stack and in last iterate the stack and add each character into a new string.
Example:
Input: str="Hello Word"
Output: droW olleH
Approach
Java
public class ReverseStringUsingStack {public static void main(String[] args) {String str = "Hello Word";Stack<Character> rev = revStrUsingStack(str);System.out.println("Reverse String is ");while (!rev.isEmpty()) {System.out.print(rev.pop());}}// Method used for reverse the given stringprivate static Stack<Character> revStrUsingStack(String str) {// declare stack to hold characterStack<Character> rev = new Stack<Character>();// Iterate till end of stringfor (int i = 0; i < str.length(); i++) {// push to stackrev.add(str.charAt(i));}return rev;}}
C++
#include <bits/stdc++.h>using namespace std;//function to reverse a stringstring reverseString(string str){//character stack to hold the//the current current characterssstack<char> st;for(int i=0;i<str.size();i++)st.push(str[i]);string reverse="";//iterate till the stack is//not emptywhile(!st.empty()){reverse+=st.top();st.pop();}return reverse;}int main(){string str = "Hello Word";string reverse=reverseString(str);cout<<reverse;return 0;}
No comments:
Post a Comment