1.给出后缀表达式计算结果
#include<iostream>
#include<cstring>
#include<stack>
using namespace std;
int My_stack[500];
int top=0;
stack<int>s;//看看stl容器
int main()
{
char a[500];
cin.getline(a,500);
int i=0,x=0,t1,t2;
while(a[i]!='#')
{
if(a[i]>='0' && a[i]<='9') {
x=0;
while(a[i]>='0' && a[i]<='9')
{
x=x*10+a[i]-'0';
i++;
}
s.push(x);
//My_stack[++top]=x;
}
if(a[i]=='+')
{
// t1=My_stack[top--];
// t2=My_stack[top--];
// My_stack[++top]=t1+t2;
t1=s.top();
s.pop();
t2=s.top();
s.pop();
s.push(t1+t2);
}
else if(a[i]=='*')
{
// t1=My_stack[top--];
// t2=My_stack[top--];
// My_stack[++top]=t1*t2;
t1=s.top();
s.pop();
t2=s.top();
s.pop();
s.push(t1*t2);
}
else if(a[i]=='-')
{
// t2=My_stack[top--];
// t1=My_stack[top--];
// My_stack[++top]=t1-t2;
t1=s.top();
s.pop();
t2=s.top();
s.pop();
s.push(t2-t1);
}
else if(a[i]=='/')
{
// t2=My_stack[top--];
// t1=My_stack[top--];
// My_stack[++top]=t1/t2;
t1=s.top();
s.pop();
t2=s.top();
s.pop();
s.push(t2/t1);
}
i++;
}
//cout<<My_stack[top];
cout<<s.top();
return 0;
}
2.验证出栈序列合法性,并给出合法序列的出栈顺序
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<stack>
const int N=1000;
int a[N],b[N];
int n;
using namespace std;
int main(){
cin>>n;
stack<int>sta;
for(int i=1;i<=n;i++){
cin>>a[i];
}
for(int i=1;i<=n;i++){
cin>>b[i];
}
int p=1;
for(int i=1;i<=n;i++){
sta.push(a[i]);
while(!sta.empty()&&sta.top()==b[p]){
sta.pop();
p++;
}
}
if(sta.empty()){
cout<<p-1;
}
else{
cout<<0;
}
//cout<<endl<<p-1;
return 0;
}
第二题说明:
a: 1 2 3 4 5
b: 5 4 3 2 1
以b作为判断序列,输入a先入栈,如果不等于b[position],说明如果合法这个应该在栈里面,不做处理,如果等于,一起出栈,p++,继续往后判断是否相等,最后所有结束之后看看栈是否为空,如果空就是合法,否则非法。
3 给出一个01序列,1入栈0出栈,判断是否合法,合法输出1,否则输出0
#include<iostream>
#include<cmath>
#include<string>
#include<algorithm>
#include<iomanip>
#include<vector>
#include<stack>
using namespace std;
int main(){
stack<int>s;
int n;
int b=0;
int num;
cin>>n;
for(int i=1;i<=n;i++){
cin>>num;
if(num==1){
s.push(num);
}
if(num==0){
if(s.empty()){
b=1;
}
else{
s.pop();
}
}
}
if(b==1||!s.empty()){
cout<<0;
}
else{
cout<<1;
}
return 0;
}