算法思路:
遍历中缀表达式中的数字和符号
对于数字: 直接输出
对于符号:
左括号: 进栈
运算符号:与栈顶符号进行优先级比较
若栈顶符号优先级高,此符号入栈
若栈顶符号优先级低,则将栈顶符号出栈并输出,之后此符号进栈
右括号:将栈顶符号弹出并输出,直到匹配左括号
遍历结束: 将栈中的所有符号弹出并输出
// 栈的应用中缀转后缀算法.cpp : 定义控制台应用程序的入口点。
//
#include "stdafx.h"
#include"LinkStack.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include"linklist.h"
int isNumber(char c)
{
return('0'<=c) && (c<='9');
}
int isOperator(char c)
{
return (c == '+') || (c == '-') || (c == '*') || (c == '/');
}
int isLeft(char c)
{
return(c == ('('));
}
int isRight(char c)
{
return(c == (')'));
}
void output(char c)
{
if (c!='\0')
{
printf("%c",c);
}
}
int priority(char c)
{
int ret = 0;
if ((c=='+')||(c=='-'))
{
ret = 1;
}
if ((c == '*') || (c == '/'))
{
ret = 2;
}
return ret;
}
void transform(const char* exp)
{
int i = 0;
LinkStack* stack = Stack_Create();
while (exp[i]!='\0')
{
if (isNumber(exp[i]))
{
output(exp[i]);
}
else if (isOperator(exp[i]))
{
while (priority(exp[i])<=priority((char)(int)Stack_Top(stack)))
{
output((char)(int)Stack_Pop(stack));
}
Stack_Push(stack,(void*)(int)exp[i]);
}
else if(isLeft(exp[i]))
{
Stack_Push(stack, (void*)(int)exp[i]);
}
else if (isRight(exp[i]))
{
while (!isLeft((char)(int)Stack_Top(stack)))
{
output((char)(int)Stack_Pop(stack));
}
Stack_Pop(stack);
}
else
{
printf("invalid exp");
break;
}
i++;
}
while (Stack_Size(stack)>0&&exp[i]=='\0')
{
output((char)(int)Stack_Pop(stack));
}
Stack_Destory(stack);
}
int main()
{
transform("8+(3-1)*5");
printf("\n");
system("pause");
return 0;
}