栈
栈的标准模板库及其使用如下。
#include<stack>
stack<int> S;
S.push(i);
int x = S.top();
S.pop();
例3.1 括号匹配问题
代码3.1
#include<iostream>
#include<stack>
#include<string.h>
using namespace std;
int main(){
stack<char> S;
string buf;
char ans[105];
int i;
while(cin >> buf){
int max = buf.length();
for(i=0;i<max;i++){
if(buf[i] == '('){
S.push(i);
ans[i] = ' ';
}
else if(buf[i] == ')'){
if(S.empty())
ans[i] = '?';
else{
S.pop();
ans[i] = ' ';
}
}
else{
ans[i] = ' ';
}
}
int x;
while(!S.empty()){
x = S.top();
S.pop();
ans[x] = '$';
}
for(i=0;i<max;i++)
cout << buf[i];
cout << endl;
for(i=0;i<max;i++)
cout << ans[i];
cout << endl;
}
return 0;
}
例3.2 简单计算器
代码3.2
#include<iostream>
#include<stack>
using namespace std;
char str[205];
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
};
stack<int> op;
stack<double> in;
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 += 2;
return ;
}
retn = 0;
for(;str[i] != ' ' && str[i] != 0;i++){
retn *= 10;
retn += str[i] - '0';
}
if(str[i] == ' ')
i++;
return;
}
int main(){
while(gets(str)){
if(str[0] == '0' && str[1] == 0)
break;
while(!op.empty())
op.pop();
while(!in.empty())
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){
int ret = op.top();
op.pop();
double b = in.top();
in.pop();
double a = in.top();
in.pop();
if(ret == 1)
tmp = a + b;
else if(ret == 2)
tmp = a - b;
else if(ret == 3)
tmp = a * b;
else
tmp = a / b;
in.push(tmp);
}
op.push(retnum);
}
}
if(op.size() == 2 && op.top() == 0)
break;
}
printf("%.2f\n",in.top());
}
return 0;
}
堆栈的使用
#include<iostream>
#include<stack>
using namespace std;
stack<int> S;
int main(){
int N;
int num;
char op;
while(cin >> N){
while(!S.empty())
S.pop();
while(N--){
cin >> op;
if(op == 'P'){
cin >> num;
S.push(num);
}
else if(op == 'O'){
if(!S.empty())
S.pop();
}
else if(op == 'A'){
if(S.empty())
cout << 'E' << endl;
else
cout << S.top() << endl;
}
}
cout << endl;
}
return 0;
}
表达式求值
坑待填。