(1)栈
栈和stack
遇到数字将其入栈,遇到运算符就将栈顶两个元素输出计算后再放回栈顶。
#include <bits/stdc++.h>
using namespace std;
stack<long long> n;
int x,y;
char str[100100];
void Get(){x=n.top();n.pop();y=n.top();n.pop();}
int main(){
while(gets(str)){
for(int i=0;str[i]!='\0';i++){
switch(str[i]){
case '+':Get();n.push(x+y);break;
case '-':Get();n.push(y-x);break;
case '*':Get();n.push(x*y);break;
case '/':Get();n.push(y/x);break;
case '^':Get();n.push(pow(y,x));break;
case ' ':break;
default :n.push(str[i]-'0');
}
}
printf("%d\n",n.top());
}
return 0;
}
(2)模拟栈
原理和上面相同,只不过没有直接用栈,而是用个普通数组将栈模拟了出来。
#include <bits/stdc++.h>
using namespace std;
long long stk[100100];
char str[100100];
int main(){
while(gets(str)){
long long pos=0;
for(int i=0;str[i]!='\0';i++){
if(str[i]=='+'){
stk[pos-1]=stk[pos-1]+stk[pos];
stk[pos]=0;
pos--;
}
else if(str[i]=='-'){
stk[pos-1]=stk[pos-1]-stk[pos];
stk[pos]=0;
pos--;
}
else if(str[i]=='*'){
stk[pos-1]=stk[pos-1]*stk[pos];
stk[pos]=0;
pos--;
}
else if(str[i]=='/'){
stk[pos-1]=stk[pos-1]/stk[pos];
stk[pos]=0;
pos--;
}
else if(str[i]=='^'){
stk[pos-1]=pow(stk[pos-1],stk[pos]);
stk[pos]=0;
pos--;
}
else if(str[i]==' '){
continue;
}
else{
stk[++pos]=str[i]-'0';
}
}
cout<<stk[1];
}
return 0;
}