Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- Evaluation Of postfix Expression in C++
- Input Postfix expression must be in a desired format.
- Operands must be integers and there should be space in between two operands.
- operands only have one num number.It's not fit like: 23 45*
- Only '+' , '-' , '*' and '/' operators are expected.
- */
- /**pseudo code
- * Evaluatepostfix(exp)
- * {
- * create a stack S
- * for i =0 to legth(exp)-1
- * {
- * if(exp[i] is operand)
- * s.push(exp[i])
- * else if(exp[i] is operator)
- * {
- * op1 =top()
- * pop()
- * op2 = top()
- * pop()
- * result <--perform(exp[i],op1,op2)
- * push(res)
- * }
- *
- *
- * }
- *
- * }
- *
- */
- #include <iostream>
- #include <stack>
- #include<queue>
- using namespace std;
- // Function to evaluate Postfix expression and return output
- int EvauatePostfix(string expression)
- {
- // Declaring a Stack from Standard template library in C++.
- stack<int> stack1;
- int temp, operand1, operand2;
- for (int i = 0; i < expression.size(); i++) {
- // Scanning each character from left.
- // If character is a delimitter, move on.
- if (expression[i] == ' ' || expression[i] == ',')
- continue;
- else if (expression[i] >= '0' && expression[i] <= '9') {
- stack1.push(expression[i] - '0');
- }
- // If character is operator, pop two elements from stack,
- // perform operation and push the result back.
- else if (expression[i] == '+' || expression[i] == '-' || expression[i] == '*' || expression[i] == '/') {
- operand2 = stack1.top();
- stack1.pop();
- operand1 = stack1.top();
- stack1.pop();
- switch (expression[i]) {
- case '+':temp = operand1 + operand2;
- stack1.push(temp);
- break;
- case '-':temp = operand1 - operand2;
- stack1.push(temp);
- break;
- case '*':temp = operand1 * operand2;
- stack1.push(temp);
- break;
- case '/':temp = operand1 / operand2;
- stack1.push(temp);
- break;
- default:cout << "Unexpected Error \n";
- return -1;
- }
- }
- else
- cout << "Unexpected Error \n";
- return -1;
- }
- return temp;
- }
- int main()
- { //parse the postfix expressions
- //test string string string1 = "23*54*+9-";
- string expression;
- cout << "Enter Postfix Expression \n";
- getline(cin, expression);
- int result = EvauatePostfix(expression);
- cout << "Output=" << result << endl;
- // std::cout << "Hello, World!" << std::endl;
- return 0;
- }
Add Comment
Please, Sign In to add comment