思路:
1.从左到右获取中缀表达式
2. *,/ 的优先级最高,遇到直接入栈,直到遇到比他优先级低的,依次出栈
3.(,遇到直接入栈,等遇到右括号 )后,将( 后入栈的运算符出栈输出,( 出栈不输出
4.+ - ,如果栈空,直接入栈,否则将栈中优先级不低于它们的运算符依次弹出,直到栈空或遇到 )为止
代码如下所示:
//中缀转后缀
void Change(char str[], Stack S)
{
int i = 0;
while (str[i] != '\0')
{
while (isdigit(str[i]))
{
printf("%c", str[i++]);
if (!isdigit(str[i]))
printf(" ");
}
//'+','-'优先级最低
if (str[i] == '+' || str[i] == '-')
{
if (IsEmpty(S))
Push(str[i], S);
else
{
if(Top(S)=='(')
Push(str[i],S);
else
{
while (!IsEmpty(S))
{
if(Top(S) != '(')
{
printf("%c ", Top(S));
Pop(S);
}
else
break;
}
Push(str[i], S);
}
}
}
else if (str[i] == ')')
{
while (Top(S) != '(')
{
printf("%c ", Top(S));
Pop(S);
}
Pop(S);
}
else if (str[i] == '*' || str[i] == '/' || str[i] == '(')
Push(str[i], S);
else if (str[i] == '\0')
break;
else
{
printf("input error");
return;
}
i++;
}
while(!IsEmpty(S))
{
printf("%c ", Top(S));
Pop(S);
}
}
完整程序如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
//栈的定义
struct Node
{
int Capacity; //容量
int TopOfStack; //栈顶
char *Array;
} Node;
typedef struct Node *Stack, *PtrNode;
//创建栈
Stack CreatStack(int Max)
{
Stack S;
S = (PtrNode)malloc(sizeof(struct Node));
if (S == NULL)
printf("create stack error");
S->Array = (char *)malloc(Max * sizeof(char));
if (S->Array == NULL)
printf("create stack error");
S->Capacity = Max;
S->TopOfStack = -1;
return S;
}
int IsFull(Stack S)
{
return S->TopOfStack == S->Capacity - 1;
}
int IsEmpty(Stack S)
{
return S->TopOfStack == -1;
}
void Push(char x, Stack S)
{
if (IsFull(S))
printf("stack is full");
else
{
S->TopOfStack=S->TopOfStack+1;
S->Array[S->TopOfStack]=x;
}
// S->Array[++S->TopOfStack] = x;
}
void Pop(Stack S)
{
if (IsEmpty(S))
printf("stack is empty");
else
S->TopOfStack--;
}
char Top(Stack S)
{
if (IsEmpty(S))
printf("stack is empty");
else
return S->Array[S->TopOfStack];
}
//中缀转后缀
void Change(char str[], Stack S)
{
int i = 0;
while (str[i] != '\0')
{
while (isdigit(str[i]))
{
printf("%c", str[i++]);
if (!isdigit(str[i]))
printf(" ");
}
//'+','-'优先级最低
if (str[i] == '+' || str[i] == '-')
{
if (IsEmpty(S))
Push(str[i], S);
else
{
if(Top(S)=='(')
Push(str[i],S);
else
{
while (!IsEmpty(S))
{
if(Top(S) != '(')
{
printf("%c ", Top(S));
Pop(S);
}
else
break;
}
Push(str[i], S);
}
}
}
else if (str[i] == ')')
{
while (Top(S) != '(')
{
printf("%c ", Top(S));
Pop(S);
}
Pop(S);
}
else if (str[i] == '*' || str[i] == '/' || str[i] == '(')
Push(str[i], S);
else if (str[i] == '\0')
break;
else
{
printf("input error");
return;
}
i++;
}
while(!IsEmpty(S))
{
printf("%c ", Top(S));
Pop(S);
}
}
int main()
{
char str[100];
scanf("%s", str);
int len = strlen(str);
Stack S = CreatStack(len + 1);
Change(str, S);
system("pause");
}
/*
样例:
2*(9+6/3-5)+4
2 9 6 3 / + 5 - * 4 +
5-8*(6+7)+9/4
5 8 6 7 + * - 9 4 / +
*/