括号匹配问题:
#include <iostream>
using namespace std;
int main() {
char ch[100][110]= {0},zh[110],mb[110]; //分别是输入,栈数组,目标输出
int zhl=0,chl=0;//栈顶下标和输入次数
cin.getline(ch[chl],200);//输入第一次
while(strlen(ch[chl])!=0) { //因为最后一次输入为空,所以要遍历0~chl-1
chl++;
cin.getline(ch[chl],200);
}
for(int x=0; x<chl; x++) {
//初始化
int wl[100];//左括号下标栈
zhl=0;
for(int i=0; i<110; i++) {
zh[i]=0;
mb[i]=0;
}
cout<<ch[x]<<endl;
int l=0;
while(ch[x][l]!='\0') {
l++;
}
for(int i=0; i<=l; i++) {
if(ch[x][i]=='(') { //压栈
mb[i]='(';
zh[zhl]='(';
wl[zhl]=i;
zhl++;
zh[zhl]='\0';
} else if(ch[x][i]==')') {
if(zhl>0) { //出栈
mb[i]=' ';
zh[zhl-1]='\0';
wl[zhl-1]=-1;
zhl--;
} else mb[i]='?'; //不匹配
} else if(ch[x][i]=='\0')mb[i]=='\0'; //结尾
else mb[i]=' ';//替换其他字符为空格
}
for(int i=0; i<zhl; i++) { //将下标栈剩余元素所对应的字符改为$
mb[wl[i]]='$';
}
for(int i=l-1; i>=0; i--) { //将其他左括号替换为空格
if(mb[i]=='(')mb[i]=' ';
}
for(int i=0; i<l; i++) { //输出
cout<<mb[i];
}
cout<<endl;//别忘了回车
}
return 0;
}
波兰表达式:
#include <iostream>
#include <iomanip>
#include <string>
#include <math.h>
using namespace std;
int main() {
string str;
getline(cin,str);
int l=str.length();
double zh[100];
int zhl=-1;
for(int i=l-1; i>=0; i--) {
if(str[i]>='0'&&str[i]<='9'||str[i]=='.') { //判断数字字符串结尾
string s="";
while((str[i]>='0'&&str[i]<='9')||str[i]=='.') { //分割子串
s=str[i]+s;
i--;//防止反复计算同一个子串
}
zhl++;
zh[zhl]=atof(s.c_str());//string转换为const char*再转换为double
} else if(str[i]=='+') {
zh[zhl-1]=zh[zhl]+zh[zhl-1];//出栈运算入栈
zhl--;
} else if(str[i]=='-') {
zh[zhl-1]=zh[zhl]-zh[zhl-1];//出栈运算入栈
zhl--;
} else if(str[i]=='*') {
zh[zhl-1]=zh[zhl]*zh[zhl-1];//出栈运算入栈
zhl--;
} else if(str[i]=='/') {
zh[zhl-1]=zh[zhl]/zh[zhl-1];//出栈运算入栈
zhl--;
}
}
cout<<fixed<<setprecision(6)<<zh[0];//输出
return 0;
}