后缀运算–洛谷有题
#include <bits/stdc++.h>
using namespace std;
int main()
{
string p;
string::iterator it;
stack<int> st;
cin >> p;
int num = 0;
for (it = p.begin(); *it != '@'; it++)
{
if (*it == '.')
{
continue;
}
else if(*it == '+'|| *it == '*'|| *it == '-'|| *it == '/')
{
int first = st.top();
st.pop();
int second = st.top();
st.pop();
if (*it == '+')
{
st.push(first + second);
}
else if (*it == '*')
{
st.push(first * second);
}
else if (*it == '-')
{
st.push(-(first - second));
}
else if (*it == '/')
{
st.push(second / first);
}
}
else
{
if (*(it + 1) >= '0' && *(it + 1) <= '9')
{
num++;
}
else
{
int value=0;
for (int i = num; i >=1; i--)
{
value += pow(10, i)*(*(it-i)-'0');
}
value += (*it-'0');
st.push(value);
num = 0;
}
}
}
cout << st.top();
return 0;
}
中缀转后缀
#include <bits/stdc++.h>
using namespace std;
int main()
{
string p;
cin >> p;
string::iterator it;
stack<char> st;
for (it = p.begin(); it != p.end(); it++)
{
if (isdigit(*it))
{
cout << *it;
}
else
{
if (st.empty())
{
st.push(*it);
}
else
{
if (*it == '*' ||*it == '/'||*it=='(')
{
st.push(*it);
}
else if (*it == ')')
{
while (st.top()!='(')
{
cout << st.top();
st.pop();
}
st.pop();
}
else
{
if(st.top() == '*' || st.top() == '/')
{
while (!st.empty())
{
cout << st.top();
st.pop();
}
}
st.push(*it);
}
}
}
}
while (!st.empty())
{
cout << st.top();
st.pop();
}
return 0;
}