类似表达式求值的题目
和表达式求值的做法也差不多
用两个栈分别储存 操作数 和 运算符
运算符的优先级 为 ! > & > |
有个地方需要注意的是,如果是! 与 ! 自己进行比较, 应该当作 ! < !本身来处理,否则出现 !!!F 这种表达式的时候会出现RE
因为第二个! 准备进栈时,如果此时处理 第一个!,储存操作数的栈为空栈,如果此时调用pra.top() 就会出现RE
代码如下:
#include <iostream>
#include <stack>
#include <string>
using namespace std;
int compare(char a,char b);
int main()
{
string buffer;
int ca(1);
while (getline(cin,buffer))
{
buffer.push_back('#'); //表达式最后插入一个‘#’,用来确保表达式能处理完
stack<char> pra;
stack<char> ope;
ope.push('#'); //第一个元素为‘#’ 为假定的另一种括号,优先级最低,用来判定表达式有没有处理完
int i(0);
int len = buffer.size();
while (i<len)
{
if(buffer[i]==' ') {++i;continue;}
if (buffer[i]=='F'||buffer[i]=='V')
{
pra.push(buffer[i]);
}
else
{
if (compare(ope.top(),buffer[i])<0)
ope.push(buffer[i]);
else if (compare(ope.top(),buffer[i])>0)
{
char a,b;
switch (ope.top())
{
case '!':
a=pra.top();
pra.pop();
if (a=='V') a='F';
else a='V';
pra.push(a);
break;
case '&':
a=pra.top();
pra.pop();
b=pra.top();
pra.pop();
if(a=='F'||b=='F') pra.push('F');
else pra.push('V');
break;
case '|':
a=pra.top();
pra.pop();
b=pra.top();
pra.pop();
if(a=='V'||b=='V') pra.push('V');
else pra.push('F');
break;
}
ope.pop();
continue;
}
else
{
ope.pop();
}
}
++i;
}
cout<<"Expression "<<ca++<<": ";
cout<<pra.top()<<endl;
}
return 0;
}
int compare(char a,char b) //比较运算符的优先级,需要注意的是运算符间的优先级关系并不是绝对的
{
if (b=='(') return -1;
switch (a)
{
case '(':
if (b==')') return 0;
return -1;
case '!':
if(b!='!')
return 1;
return -1;
case '&':
if (b=='!') return -1;
return 1;
case '|':
if (b=='!'||b=='&') return -1;
return 1;
case '#':
if (b=='#') return 0;
return -1;
}
return 0;
}