//用栈实现中缀表达式转为后缀表达式
//采用的存储结构为顺序存储结构
#include <iostream>
using namespace std;
#define MAXSIZE 100
//栈的结构体
struct Node
{
int *base;
int *top;
int stackSize;
};
//初始化栈的操作
void initStack(struct Node &S)
{
S.base = new int [MAXSIZE];
if(S.base == NULL)
{
cout<<"地址分配失败\n";
exit(1);
}
S.top = S.base;
S.stackSize = MAXSIZE;
}
//入栈操作
void push(struct Node &S,char e)
{
if(S.top-S.base == S.stackSize)
{
cout<<"此栈已经满了\n";
exit(1);
}
*S.top++ = e;
}
//出栈操作
void pop(struct Node &S,char &e)
{
if(S.top==S.base)
{
cout<<"栈为空\n";
exit(1);
}
e = *--S.top;
}
//运算符优先级的函数
char compare(char ch,char ch_1)
{
if(ch=='+'||ch=='-')
{
if(ch_1=='+'||ch_1=='-'||ch_1==')'||ch_1=='#')
{
return '>';
}
else if(ch_1=='*'||ch_1=='/'||ch_1=='(')
{
return '<';
}
}
if(ch=='*'||ch=='/')
{
if(ch_1=='+'||ch_1=='-'||ch_1=='*'||ch_1=='/'||ch_1==')'||ch_1=='#')
{
return '>';
}
else if(ch_1=='(')
{
return '<';
}
}
if(ch=='(')
{
if(ch_1==')')
{
return '=';
}
else if(ch_1!='#')
{
return '<';
}
else
{
cout<<"出错了\n";
exit(1);
}
}
if(ch==')')
{
if(ch_1!='(')
{
return '>';
}
else
{
cout<<"出错了\n";
}
}
if(ch=='#')
{
if(ch_1 == '#')
{
return '=';
}
else if(ch_1!=')')
{
return '<';
}
else
{
cout<<"出错了\n";
}
}
}
//取栈顶元素
char getTop(struct Node S)
{
char e;
if(S.base==S.top)
{
cout<<"栈为空\n";
exit(1);
}
e = *--S.top;
return e;
}
//实现功能的函数
void function(struct Node S)
{
char ch;
cout<<"请输入你要转换的中缀表达式(以#号作为结束符)\n";
cin>>ch;
while(ch!='#')
{
if(ch>='1'&&ch<='9'||ch>='A'&&ch<='Z'||ch>='a'&&ch<='z')
{
cout<<ch<<" ";
}
else
{
char e;
e = getTop(S);
if(ch==')')
{
while(getTop(S)!='(')
{
pop(S,e);
cout<<e<<" ";
}
pop(S,e);
}
else
{
char result = compare(e,ch);
if(result=='<')
{
push(S,ch);
}
else if(result=='>')
{
pop(S,e);
cout<<e<<" ";
push(S,ch);
}
}
}
cin>>ch;
}
char e;
if(ch=='#')
{
while(getTop(S)!='#')
{
pop(S,e);
cout<<e<<" ";
}
}
}
int main()
{
struct Node S;
initStack(S);
push(S,'#');
function(S);
return 0;
}