线性表二——栈stack
第一题
#include<bits/stdc++.h>
using namespace std;
stack<char> s;
int n;
string ced;//如何匹配 出现的右括号转换成同类型的左括号,方便我们直接和栈顶元素
char cheak(char c){if(c==')') return '(';if(c==']') return '[';if(c=='}') return '{';return '\0';//如果传入的不是右括号,匹配失败,这里认为规定失败返回空
} int main(){cin>>n;getchar();//读取输入流中剩下的回车,在n后面的回车 while(n--){//清空上一轮的数据while(!s.empty()) s.pop();getline(cin,ced);//读入空串 for(int i=0;i<ced.size();i++){if(s.empty()) s.push(ced[i]);else {char tmp=cheak(ced[i]);// 如果传入一个左括号,一定无法匹配,也就一定会入栈if(tmp!=s.top()) s.push(ced[i]);else s.pop(); }} if(s.empty()) cout<<"Yes"<<endl;else cout<<"No"<<endl;}return 0;
}
第二题
#include<bits/stdc++.h>
using namespace std;
char sy;
stack<int> s;
int main(){//如何取出字符串中的每个数字 ,利用getchar的特性 sy=getchar();while(sy!='@'){//1、要把后面连在的一起的数字全部取出 if(sy>='0'&&sy<='9'){int num=sy-'0';//num保存由字符转换过来的数字while(1){sy=getchar();if(sy>='0'&&sy<='9')//读入的字符仍旧是数字字符num=num*10+sy-'0'; else break;} //cout<<num<<endl;s.push(num);//读取出的数入栈 }//提前排出字符。if(sy=='.') {sy=getchar();continue;}int a=s.top(); s.pop();int b=s.top(); s.pop();switch(sy){//可以提前取出和弹出两个栈顶 case '+':s.push(b+a);break;case '-':s.push(b-a);break;case '*':s.push(b*a);break;case '/':s.push(b/a);break;} sy=getchar(); } cout<<s.top();return 0;
}