期末数据结构程序设计~设计一个程序,演示用算符优先法对算术表达式求值的过程。注意·~不要C++的 是数据

#include

算符优先分析法实验报告 算符优先分析器实验报告算符优先分析法实验报告 算符优先分析器实验报告


算符优先分析法实验报告 算符优先分析器实验报告


算符优先分析法实验报告 算符优先分析器实验报告


using namespace std;

const int InitSize=100;

const int IncreastSize=10;

template

class SqStack {

private:

datatype base;

datatype top;

int stacksize;

public:

SqStack();

void DestroyStack();

void ClearStack();

int StackLength();

bool IsEmpty();

bool GetTop(datatype &e);

bool Pop(datatype &e);

bool Push(datatype e);

};

template

SqStack::SqStack()

{base=new datatype[InitSize];

if(!base)exit(1);

top=base;

stacksize=InitSize;

}template

void SqStack::DestroyStack()

{delete[] base;

base=top=NULL;

stacksize=0;

}template

void SqStack::ClearStack()

{top=base;

}template

int SqStack::StackLength()

{return top-base;

}template

bool SqStack::IsEmpty()

{if(top==base)

return fasle;

else return true;

}template

bool SqStack::GetTop(datatype &e)

{if(top==base)

return false;

e=(top-1);

return true;

}template

bool SqStack::Pop(datatype &e)

{if(top==base)

return false;

e=(top-1);

top--;

return true;

}template

bool SqStack::Push(datatype e)

{if(top-base>=stacksize)

{base=(datatype )realloc( base , (stacksize+IncreastSize)sizeof(int) );

if(!base)exit(1);

top=base+stacksize;

stacksize+=IncreastSize;

}(top)=e;

top++;

return true;

}int com(char m,char t)

{if(t=='(') return -1;

else if(t==')')

{if(m=='+'||m=='-'||m==''||m=='/') return 1;

else if(m=='(') return 0;

else return -2;

}else if(t==''||t=='/')

{if(m=='+'||m=='-'||m=='#'||m=='(') return -1;

else return 1;

}else if(t=='+'||t=='-')

{if(m=='#'||m=='(') return -1;

else return 1;

}else

{if(m=='#')return 0;

else if(m=='+'||m=='-'||m==''||m=='/') return 1;

else return -2;

}}

void main()

{SqStack op;

SqStack re;

char t,m;

double result,flag=1;

op.Push('#');

t=getchar();

while(true){

if(t>='0'&&t<='9')

{double s=0;

s=s10+t-'0';

t=getchar();

while(t>='0'&&t<='9' )

{s=s10+t-'0';

t=getchar();

}re.Push(s);

}else if(t=='+'||t=='-'||t==''||t=='/'||t=='('||t==')'||t=='n')

{ op.GetTop(m);

while(com(m,t)==1 )

{double x1,x2;

op.Pop(m);

if(re.Pop(x2)&&re.Pop(x1))

{if(m=='+') re.Push(x1+x2);

else if(m=='-') re.Push(x1-x2);

else if(m=='') re.Push(x1x2);

else if(m=='/') {if(x2!=0)re.Push(x1/x2); else flag=0;}

}else flag=0;

op.GetTop(m);

}if(com(m,t)==-1)

op.Push(t);

else if(com(m,t)==0)

op.Pop(m);

else flag=0;

if(!op.GetTop(m)) break;

t=getchar();

}else t=getchar();

}if(re.GetTop(result)&&flag)

cout<

else cout<<"Input error!n";

}

算符优先分析法的介绍

算符文法:即它的任一产生式的右部都不含两个相继的非终结符的文法。如果G是一个不含空字符的算法文法,那么只要它的任一对终结符都至多只满足>,=,<的关系的其中一种,则称g是一个算符优先文法。< p=>