数据结构课堂测试三题

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;
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值