本帖最后由 mupa 于 2016-3-30 18:47 编辑 #include <iostream>
using namespace std;
class stack
{
public:
void clearstack();
int isempty();
int length();
char gettop();
int push(char);
int pop(char*);
int traverse();
protected:
char *top;
char *base;
};
void stack::clearstack()
{
top=base;
}
int stack::isempty()
{
if(top==base)
{
return 1;
}
else
{
return 0;
}
}
int stack::length()
{
return top-base;
}
char stack::gettop()
{
return *(top-1);
}
int stack::push(char c)
{
*top=c;
top++;
return 1;
}
int stack::pop(char *x)
{
*x=*--top;
return 1;
}
int stack::traverse()
{
if(top!=0)
{
cout<<*(--top);
}
return 1;
}
int main()
{
stack s;
char c,e;
s.clearstack();
cout<<"输入中缀表达式,#作结束标志:"<<endl;
cin>>c;
while(c != '#')
{
while(c>='0' && c<='9')
{
cout<<c;
cin>>c;
if(c<'0'||c>'9')
{
cout<<" ";
}
}
if(')'==c)
{
s.pop(&e);
while('('!=e)
{
cout<<e;
s.pop(&e);
}
}
else if('+'==c || '-'==c)
{
if(!s.length())
{
s.push(c);
}
else
{
do
{
s.pop(&e);
if('('==e)
{
s.push(e);
}
else
{
cout<<e;
}
}while(s.length() && '('!=e );
s.push(c);
}
}
else if('*'==c || '/'==c || '('==c)
{
s.push(c);
}
else if('#'==c)
{
break;
}
else
{
cout<<"输入有误"<<endl;
return -1;
}
cin>>c;
}
while(s.length())
{
s.pop(&e);
cout<<e;
}
return 0;
}
|