数据结构实验之栈三:后缀式求值

来源:互联网 发布:js怎么控制class 编辑:程序博客网 时间:2024/06/02 04:07

数据结构实验之栈三:后缀式求值

Time Limit: 1000MS Memory Limit: 65536KB
Submit Statistic

Problem Description

对于一个基于二元运算符的后缀表示式(基本操作数都是一位正整数),求其代表的算术表达式的值。

Input

输入一个算术表达式的后缀式字符串,以‘#’作为结束标志。

Output

求该后缀式所对应的算术表达式的值,并输出之。

Example Input

59*684/-3*+#

Example Output

57

Hint

基本操作数都是一位正整数!

Author

 
#include <iostream>#include <bits/stdc++.h>using namespace std;stack<int>s;int main(){    string st;    cin>>st;    for(int i = 0; st[i] != '#'; i++)    {        if(st[i] >= 48 && st[i] <= 57)        {            int t = (int)(st[i] - 48);            s.push(t);        }        else        {            int x = s.top();            s.pop();            int y = s.top();            s.pop();            if(st[i] == '+')            {                int k = y+x;                s.push(k);            }            if(st[i] == '-')            {                int k = y-x;                s.push(k);            }            if(st[i] == '*')            {                int k = y*x;                s.push(k);            }            if(st[i] == '/')            {                int k = y/x;                s.push(k);            }        }    }    cout<<s.top()<<endl;    return 0;}


原创粉丝点击