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

2025-04-03 19:03:26
推荐回答(3个)
回答1:

#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=s*10+t-'0';

t=getchar();
while(t>='0'&&t<='9' )
{s=s*10+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(x1*x2);
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";

}

回答2:

你这分数也太少了呗?至少的要一天才能搞定的!

回答3:

这个分低了,确实。。。。