In: Computer Science
Write in C++ programming language
Given the following postfix string, from left to right, use the stack push operation to put items on the stack and the pop operation whenever an operator is encountered and to get two items and apply the operator to the operands then push back the result to evaluate the expression … rewrite the entire stack as it appears before each operator is applied.
12 3 / 5 + 32 2 3 ^ 2 * / -
Here is your required code in C++
#include<bits/stdc++.h>
using namespace std;
class MyStack
{
double stack[100];
int top;
public:
//constructor
MyStack()
{
top=-1;
}
//add element to stack
void push(double data)
{
top++;
stack[top] = data;
}
//remove element from stack
double pop()
{
return stack[top--];
}
//get top element from stack
double peek()
{
return stack[top];
}
};
int main(int argc, char *argv[])
{
MyStack stack;
string line;
// Taking inputs
cout<<"\nEnter postfix expression: \n";
getline(cin, line);
stringstream expression(line);
string token;
while (expression >> token) {
if (isdigit(token[0])) {
stack.push(atof(token.data()));
}
else if (token == "+") { // Addition Operation
double x = stack.pop();
double y = stack.pop();
stack.push(y + x);
}
else if (token == "-") { // Subtraction Operation
double x = stack.pop();
double y = stack.pop();
stack.push(y - x);
}
else if (token == "*") { // Multiplication Operation
double x = stack.pop();
double y = stack.pop();
stack.push(y * x);
}
else if (token == "/") { // Division Operation
double x = stack.pop();
double y = stack.pop();
stack.push(y / x);
}
else if(token == "^"){ // Power Operation
double x = stack.pop();
double y = stack.pop();
stack.push(pow(y, x));
}
}
// Displaying result
cout<<"\nExpression evaluation result: \n";
cout << stack.peek()<<"\n";
return 0;
}
Please refer to
the screenshot of the code to understand the indentation of the
code:
Here is the Output
for the sample Test Cases: