類似表達式求值的題目
和表達式求值的做法也差不多
用兩個棧分別儲存 操作數 和 運算符
運算符的優先級 爲 ! > & > |
有個地方需要注意的是,如果是! 與 ! 自己進行比較, 應該當作 ! < !本身來處理,否則出現 !!!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;
}