您的位置:首页 > 理论基础 > 数据结构算法

数据结构实验之栈二:一般算术表达式转换成后缀式

2016-07-29 20:45 344 查看
#include<iostream>
#include<algorithm>

using namespace std;

const int maxn=10000+10;

typedef struct
{
char *data;
int top;
int sizestack;
}STACK;

void initstack(STACK &S)
{
S.data=new char [maxn];
S.top=-1;
S.sizestack=maxn;
}

void push(STACK &S, char s)
{
S.data[++S.top]=s;
}

void pop(STACK &S)
{
S.top--;
}

int cmp(char s)
{
if(s=='+'||s=='-')
return 1;
if(s=='*'||s=='/')
return 2;
if(s=='(')
return 3;
if(s==')')
return 4;
return 0;
}

int main()
{
ios::sync_with_stdio(false);
char s;
STACK S;
initstack(S);
while(cin>>s&&s!='#')
{
if(s>='a'&&s<='z')
{
cout<<s;
}
else
{
if(S.top==-1)
{
push(S, s);
}
else if(cmp(s)>=cmp(S.data[S.top]))
{
if(cmp(s)==4)
{
while(S.data[S.top]!='(')
{
cout<<S.data[S.top--];
}
pop(S);
}
else
{
push(S, s);
}
}
else
{
if(S.data[S.top]!='(')
{
cout<<S.data[S.top];
S.data[S.top] = s ;
}
else
push(S, s);
}
}
}
while(S.top>=0)
{
cout<<S.data[S.top];
S.top--;
}
cout<<endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: