#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 50
typedef struct
{
char data[MAXSIZE];
int top;
}SqStack;
void InitSqStack(SqStack &S)
{
S.top=-1;
}
bool StackEmpty(SqStack S)
{
if (S.top==-1)
return true;
return false;
}
bool Push(SqStack &S,char e)
{
if (S.top==MAXSIZE-1)
return false;
S.data[++S.top]=e;
return true;
}
bool Pop(SqStack &S,char &e)
{
if (S.top==-1)
return false;
e=S.data[S.top--];
return true;
}
bool GetTop(SqStack S,char &e)
{
if (S.top==-1)
return false;
e=S.data[S.top];
return true;
}
void Destory(SqStack &S)
{
S.top=-1;
}
char connect(char a[],char b[])
{
int i=0,j=0;
while (a[i]!='\0'||a[i]!=' ')
{
i++;
}
while (b[j]!='\0')
{
a[i++]=b[j++];
}
return a[i];
}
int getpriority(char a)
{
if (a=='+'||a=='-'){
return 1;}
if (a=='/'||a=='*'){
return 2;}
if (a=='('){
return 3;}
return 0;
}
//A+B*(C-D)-E/F转成后缀表达式
//中缀转后缀
//1.遇到操作数。直接加入后缀表达式
//2.遇到界限符。遇到“(”直接入栈;遇到“)”,则依次弹出栈内运算符并加入后缀表达式,直到弹出“(”为止。
//3.遇到运算符。依次弹出栈中优先级高于或等于当前运算符的所有运算符,并加入后缀表达式。若碰到“(”或栈空,则停止。之后再把当前运算符入栈。
int main()
{
SqStack S;
char str1[MAXSIZE],e;
int i=0,x;
printf("Input:");
gets(str1);
InitSqStack(S);//初始化栈
while (str1[i]!='\0')
{
if (str1[i]>='0'&&str1[i]<='9')//如果str[i]字符为数字,则输出
{
printf("%c",str1[i]);
}
if (str1[i]=='(')//如果str[i]字符是'(',则入栈
{
Push(S,str1[i]);
// printf("Push:%c\n",str1[i]);
}
if (str1[i]==')')//如果str[i]字符是')',则进行匹配弹出
{
e='0';
while (e!='(')//栈中的字符依次弹出直到其字符等于')'
{
Pop(S,e);
// printf("Pop:%c\n",e);
if (e!='(')//当字符不为'('弹出
{
printf("%c",e);
}
}
}
if (str1[i]=='-'||str1[i]=='+'||str1[i]=='*'||str1[i]=='/')//当str[i]字符是运算符时
{
if (StackEmpty(S))//若是空栈,则直接入栈
{
Push(S,str1[i]);
// printf("Push1:%c\n",str1[i]);
}else{
// GetTop(S,e);
// printf("Top:%c\n",e);
while(getpriority(e)>=getpriority(str1[i])&&e!='('&&!StackEmpty(S))//输出栈中字符直到栈中字符的优先级小于str[i]字符优先级且栈不为空
{
Pop(S,e);
// printf("Pop:%c\n",e);
printf("%c",e);
}
Push(S,str1[i]);
// printf("Push:%c\n",str1[i]);
}//
}
if (!StackEmpty(S)&&str1[i+1]=='\0')//栈不空且下一个字符为结束符时,依次输出栈中字符
{
while (!StackEmpty(S))//
{
Pop(S,e);
// printf("Pop:%c\n",e);
printf("%c",e);
}
}
i++;//字符++
}
return 0;
}
仅供参考,若有不完善的地方,请大佬们指导