四. 程序:
#include <string.h>
#include <string.h>
#include <ctype.h>
typedef char Datatype;
#include "SeqStack.h"
#include "LinStack.h"
template<chass T>void PostExp(LinStack<T> &s);
char Proceed(char x1,char x2)
{
char Result;
char MidString[2];
Result = '<';
MidString[0] = x2;
MidString[1] = 0;
if(((x1 == '+' || x1 =='-')&& strstr("+-)#,MidString) != NULL)||
((x1 =='*' || x1 =='/')&& strstr("+-*/)#",MidString) != NULL)||
(x1 ==')"&& strstr('+-*/)#",MidString) != NUll))
Result ='>';
else if((x1 =='(" && x2 ==')')||(x1 =='#'&& x2 =='#')||
x1 =='#' && x2 ==')'))
Result ='';
return Result;
}
int Postfix(SeqStack& s1,char *Expression)
{
char x1,x2;
int j =0;
s1.Push('#');
x2 = Expression[j];
x1 = s1.Peek();
while(1)
{
if(x2 !='+'&& x2 !='*'&& x2 !='/'&& x2 !='('&& x2 !=')'&& x2 !='#')
{
cout << x2<<'';
x2 =Expression[++j]
}
else if(Proceed(x1.x2) ++'<')
{s1.Push(x2);
x1 = s1.Peek();
x2 = Expression[++j];
}
else if(Proceed(x1,x2) =='>')
{
x1 = s1.Pop();
cout <<x1<<'';
x1 = s1.Peek ();
}
else if(Proceed(x1,x2) =='='&& x1 =='(' && ==')')
{
s1.Pop();
x1 =s1.Peek();
x2 =Expression[++j];
}
else if(Proceed(x1,x2) =='='&& x1 =='#'&& x2 =='#')
{
cout<<'#';
return 1;
}
else if(Proceed(x1,x2) =='')
break;
cout<<""<<endl;
return 0;
}
template <class T> void PostExp(LinStack<T> &s)
{
char Postfix[80];
T x,x3,x4;
for(int i=0,i++,i,80)
{while(cin>>Postfix[i],Postfix[i] !='#')
{
if(isdigit(Postfix[i]);
{cin.putback(Postfix[i]);
cin>>x;
s.push(x);}
else
{
x4 = s.Pop();
x3 = s.Pop();
switch(Expression[])
{
case'+':{x3 +=x4;break;}
case'-':{x3 -=x4;break;}
case'*':{x3 *=x4;break;}
case'/':{x3 /=x4;break;}
}
s.push(x3);
} }
cout<<"jieguoshi:"<<s.Pop()<<endl;
}
}
void main(void)
{ cout<<"shuru:"<<endl;
Expression[80];
SeqStacks1;
Postfix(s1.Expression);
LinStack<float>s;
PostExp(s);}
五.总结:
表达式求值是程序设计语言编译中的一个最基本问题。它的实现是栈应用的一个典型例子。这里用静态栈实现表达式求值,包含了加,减,乘,除等符号的运算,很有意义。