机试指南 3.1栈的应用 含练习
例3.2 简单计算器
#include<stack>
#include<stdio.h>
using namespace std;
int mat[][5]={1,0,0,0,0,
1,0,0,0,0,
1,0,0,0,0,
1,1,1,0,0,
1,1,1,0,0, };
char str[200];
stack<char> op;
stack<double> in;
void getOp(bool & reto,int & retn,int & i);
int main()
{
while(gets(str))
{
if(str[0]=='0'&&str[1]==0)
break;
while(op.empty()==false) op.pop();
while(in.empty()==false) in.pop();
bool retop;
int retnum;
int idx=0;
while(true){
getOp(retop, retnum, idx);
if(retop==false)
in.push((double)retnum);
else
{
double tmp;
if(op.empty()==true||mat[retnum][op.top()]==1)
op.push(retnum);
else
{
while(mat[retnum][op.top()]==0)
{
double a=in.top(); in.pop();
double b=in.top(); in.pop();
int ret=op.top(); op.pop();
if(ret==1)
tmp=b+a;
else if(ret==2)
tmp=b-a;
else if(ret==3)
tmp=b*a;
else
tmp=b/a;
in.push(tmp);
}
op.push(retnum);
}
}
if(op.size()==2&&op.top()==0)
break;
}
printf("%.2f\n",in.top());
}
return 0;
}
void getOp(bool & reto,int & retn,int & i)
{
if(i==0&&op.empty()==true)
{
reto=true;
retn=0;
return;
}
if(str[i]==0)
{
reto=true;
retn=0;
return;
}
if(str[i]>='0'&&str[i]<='9')
{
reto=false;
}
else{
reto=true;
if(str[i]=='+')
retn=1;
else if(str[i]=='-')
retn=2;
else if(str[i]=='*')
retn=3;
else if(str[i]=='/')
retn=4;
i=i+2;
return;
}
retn=0;
for(;str[i]!=' '&&str[i]!=0;i++)
{
retn=retn*10;
retn=retn+str[i]-'0';
}
if(str[i]==' ')
i++;
return;
}
练1 堆栈的使用
#include<stdio.h>
#include<stack>
using namespace std;
stack<int> s;
int main()
{
int n;
while(scanf("%d",&n)!=EOF)
{
for(int i=0;i<n;i++)
{
char op;
scanf("%c",&op);
if(op=='A')
{
if(s.empty()==true)
printf("E\n");
else
printf("%d\n",s.top());
}
else if(op=='P')
{
int num;
scanf("%d",&num);
s.push(num);
}
else if(op=='O')
{
if(s.empty()==false)
s.pop();
}
}
}
printf("\n");
return 0;
}