Task: Find the final value of given postfix expression.
Example:
Input:
1
123+*8-
Output:
-3
Here is the Code:
Program in C++:
- #include <iostream>
 - #include <bits/stdc++.h>
 - using namespace std;
 - int evalutionOfPostfix(string s)
 - {
 - stack<int> st;
 - int a,b,c;
 - for(int i=0;i<s.length();i++)
 - {
 - if(isdigit(s[i]))
 - {
 - st.push((s[i] - '0'));
 - }
 - else
 - {
 - b=st.top();
 - st.pop();
 - a=st.top();
 - st.pop();
 - if(s[i]=='*')
 - {
 - c=a*b;
 - }
 - else if(s[i]=='/')
 - {
 - c=a/b;
 - }
 - else if(s[i]=='+')
 - {
 - c=a+b;
 - }
 - else
 - {
 - c=a-b;
 - }
 - st.push(c);
 - }
 - }
 - cout<<st.top()<<endl;
 - st.pop();
 - }
 - int main()
 - {
 - int t;
 - cin>>t;
 - while(t--)
 - {
 - string s;
 - cin>>s;
 - evalutionOfPostfix(s);
 - }
 - return 0;
 - }
 
Here is the Video:
Comments
Post a Comment