
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Evaluate Postfix Notation in C++
Suppose we have postfix expression and we have to evaluate the value. Postfix expression is also known as Reverse polish notation. Here we have to use the stack data structure to solve the postfix expressions.
So if the expression is “21+3*”, then the answer will be 9.
Let us see the steps −
- for each character ch in the postfix expression, do
- if ch is an operator $\odot$ , then
- a := pop first element from stack,
- b := pop second element from the stack
- res := b $\odot$ a
- push res into the stack
- else if ch is an operand, then
- add ch into the stack
- if ch is an operator $\odot$ , then
- return element of stack top
Let us see the following implementation to get better understanding −
Example
#include<bits/stdc++.h> using namespace std; float scanNum(char ch){ int value; value = ch; return float(value-'0');//return float from character } int isOperator(char ch){ if(ch == '+'|| ch == '-'|| ch == '*'|| ch == '/' || ch == '^') return 1;//character is an operator return -1;//not an operator } int isOperand(char ch){ if(ch >= '0' && ch <= '9') return 1;//character is an operand return -1;//not an operand } float operation(int a, int b, char op){ //Perform operation if(op == '+') return b+a; else if(op == '-') return b-a; else if(op == '*') return b*a; else if(op == '/') return b/a; else if(op == '^') return pow(b,a); //find b^a else return INT_MIN; //return negative infinity } float postfixEval(string postfix){ int a, b; stack<float> stk; string::iterator it; for(it=postfix.begin(); it!=postfix.end(); it++){ //read elements and perform postfix evaluation if(isOperator(*it) != -1){ a = stk.top(); stk.pop(); b = stk.top(); stk.pop(); stk.push(operation(a, b, *it)); }else if(isOperand(*it) > 0){ stk.push(scanNum(*it)); } } return stk.top(); } main(){ string post = "21+3*"; cout <<postfixEval(post); }
Input
"21+3*"
Output
9
Advertisements