P1449 字尾表示式 棧的應用
阿新 • • 發佈:2022-03-06
棧的應用
當讀到的數時入棧,當讀到運算子時,對應資料出棧,計算後再入棧,當讀到@時,棧頂為本題的解,這裡的棧用C++stl的stack容器,簡化程式碼的實現。
//P1449 字尾表示式 #include<iostream> #include<stack> #include<cstring> using namespace std; typedef long long LL; stack <LL> sd; char bds[1001]; int main() { cin>>bds; int bdslen=strlen(bds); int i=0; while (i<bdslen) { if (bds[i]=='@') break; else if (bds[i]=='+') { int t1,t2; t1=sd.top(); sd.pop(); t2=sd.top(); sd.pop(); sd.push(t1+t2); i++; } else if (bds[i]=='-') { int t1,t2; t1=sd.top(); sd.pop(); t2=sd.top(); sd.pop(); sd.push(t2-t1); i++; } else if (bds[i]=='*') { int t1,t2; t1=sd.top(); sd.pop(); t2=sd.top(); sd.pop(); sd.push(t1*t2); i++; } else if (bds[i]=='/') { int t1,t2; t1=sd.top(); sd.pop(); t2=sd.top(); sd.pop(); sd.push(t2/t1); i++; } else { int t=0; while (i<bdslen&&bds[i]>='0'&&bds[i]<='9') { t=t*10+bds[i]-'0'; i=i+1; } sd.push(t); i=i+1; } } cout<<sd.top()<<endl; }