栈的应用
#include <stdio.h>
#include <stdlib.h>
# define maxSize 100
typedef struct //顺序栈
{
int data[maxSize];
int top;
}SqStack;
int getPriority(char op) //设置优先级
{
if(op=='-'||op=='+')
return 0;
else
return 1;
}
中缀转后缀
void infixToPostFix(char infix[], char s2[],int &top2) //转换为后缀表达式
{
char s1[maxSize]; int top1=-1; //创建栈用于保存运算符
int i=0;
while(infix[i]!='\0')
{
if('0'<=infix[i]&&infix[i]<='9')
{
s2[++top2]=infix[i];
i++;
}
else if(infix[i]=='(')
{
s1[++top1]=infix[i];
i++;
}
else if(infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/')
{
if(top1==-1||
s1[top1]=='('||
getPriority(infix[i])>getPriority(s1[top1]))
{
s1[++top1]=infix[i];
i++;
}
else
s2[++top2]=s1[top1--];
}
else if (infix[i]==')')
{
while(s1[top1]!='(')
s2[++top2]=s1[top1--];
--top1;
++i;
}
}
while(top1!=-1)
s2[++top2]=s1[top1--];
}
中缀转前缀
void infixToPreFix(char infix[],int len, char s2[],int &top2) //转换为前缀表达式
{
char s1[maxSize];int top1=-1;
int i=len-1;
while(i>=0)
{
if(infix[i]>='0'&&infix[i]<='9')
{
s2[++top2]=infix[i];
i--;
}
else if(infix[i]==')')
{
s1[++top1]=infix[i];
i--;
}
else if(infix[i]=='+'||infix[i]=='-'||infix[i]=='*'||infix[i]=='/')
{
if(top1==-1||
s1[top1]==')'||
getPriority(infix[i])>=getPriority(s1[top1]))
{
s1[++top1]=infix[i];
i--;
}
else
s2[++top2]=s1[top1--];
}
else if (infix[i]=='(')
{
while(s1[top1]!=')')
s2[++top2]=s1[top1--];
--top1;
--i;
}
}
while(top1!=-1)
s2[++top2]=s1[top1--];
}
main函数运行示例:
int main()
{
char infix[]={'(','2','+','3','+','4','*','5',')','/','6'}; //'(','2','+','3','+','4','*','5',')','/','6','\0' (1+2+3*4)/5
char s2[maxSize];
int top2=-1;
int len_s2=9;
// infixToPostFix(infix,s2,top2);
// for(int i=0;i<len_s2;i++)
// {
// printf("%c\n",s2[i]);
// }
int len=11;
infixToPreFix(infix,len,s2,top2);
for(top2;top2>=0;top2--)
{
printf("%c\n",s2[top2]);
}
}