C++實現(xiàn)逆波蘭式
(a+b)c的逆波蘭式為ab+c,假設計算機把ab+c按從左到右的順序壓入棧中,并且按照遇到運算符就把棧頂兩個元素出棧,執(zhí)行運算,得到的結果再入棧的原則來進行處理,那么ab+c的執(zhí)行結果如下:
1)a入棧(0位置)
2)b入棧(1位置)
3)遇到運算符“+”,將a和b出棧,執(zhí)行a+b的操作,得到結果d=a+b,再將d入棧(0位置)
4)c入棧(1位置)
5)遇到運算符“”,將d和c出棧,執(zhí)行dc的操作,得到結果e,再將e入棧(0位置)
經過以上運算,計算機就可以得到(a+b)*c的運算結果e了。
逆波蘭式除了可以實現(xiàn)上述類型的運算,它還可以派生出許多新的算法,數(shù)據(jù)結構,這就需要靈活運用了。逆波蘭式只是一種序列體現(xiàn)形式。
eg:
輸入示例
1 2 + 3 4 - *
輸出示例
-3
代碼
#include <iostream>
#include <stack>
#include <cstdio>
using namespace std;
int main()
{
string s;
getline(cin,s);
int n = s.length();//字符串長度
stack<int> t;
for(int i=0;i<n;i++)
{
char c=s[i];
if(c=='+'){
int a=t.top();
t.pop();
int b=t.top();
t.pop();
t.push(a+b);
}
else if(c=='-'){
int a=t.top();
t.pop();
int b=t.top();
t.pop();
t.push(b-a);
}
else if(c=='*'){
int a=t.top();
t.pop();
int b=t.top();
t.pop();
t.push(a*b);
}
else if(c=='/'){
int a=t.top();
t.pop();
int b=t.top();
t.pop();
t.push(a/b);
}
else if(c==' '){
continue;
}
else{//數(shù)字
int m=(int)c;
m=m-48;
t.push(m);
}
}
cout<<t.top();
return 0;
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
C/C++?Qt?StringListModel?字符串列表映射組件詳解
StringListModel?字符串列表映射組件,該組件用于處理字符串與列表框組件中數(shù)據(jù)的轉換,通常該組件會配合ListView組件一起使用,本文給大家介紹了C/C++?Qt?StringListModel?字符串列表映射組件的相關知識,感興趣的朋友跟隨小編一起看看吧2021-12-12
C++實現(xiàn)LeetCode(166.分數(shù)轉循環(huán)小數(shù))
這篇文章主要介紹了C++實現(xiàn)LeetCode(166.分數(shù)轉循環(huán)小數(shù))2021-07-07

