Assume that a string expression contains the following abcd
Assume that a string expression contains the following \"{(a+b)*(c+d)}\". We want to store the expression in a stack. Write the code of a function you will call:
void print_rec_rev_str(Stack str)
which will print the reverse of the above expression:
})d+c(*)b+a)}
Solution
import java.util.*;
class Main {
public static void main(String[] args) {
//Declare expression
String expression = \"{(a+b)*(c+d)}\";
// create stack object
Stack st = new Stack();
//push expression to stack
for(int i=0;i<expression.length();i++){
st.push(expression.charAt(i));
}
//call print_rec_rev_str function
print_rec_rev_str(st);
System.out.println();
}
static void print_rec_rev_str(Stack str){
// while stack is not empty
while(!str.empty()){
//print top element
System.out.print(str.peek());
//pop top element from stack
str.pop();
}
}
}
/* sample output
})d+c(*)b+a({
*/
