主要是利用顺序栈实现这个算法
1、先写一个头文件用来定义运算符的优先级
#pragma once
/*********************************************************************************************************
运算符优先级,数值越小优先级越高
*********************************************************************************************************/
#define OPERA_PRIO_PLUS_IN 4 /* 栈内 + */
#define OPERA_PRIO_MINUS_IN 4 /* 栈内 - */
#define OPERA_PRIO_MULTIPLY_IN 2 /* 栈内 * */
#define OPERA_PRIO_DIVISION_IN 2 /* 栈内 / */
#define OPERA_PRIO_LEFT_BRACKETS_IN 10 /* 栈内 ( */
#define OPERA_PRIO_PLUS_OUT 5 /* 栈外 + */
#define OPERA_PRIO_MINUS_OUT 5 /* 栈外 - */
#define OPERA_PRIO_MULTIPLY_OUT 3 /* 栈外 * */
#define OPERA_PRIO_DIVISION_OUT 3 /* 栈外 / */
#define OPERA_PRIO_LEFT_BRACKETS_OUT 1 /* 栈外 ( */
#define OPERA_PRIO_RIGHT_BRACKETS_OUT 10 /* 栈外 ) */
#define OPERA_PRIO_ERR -1 /* 运算符错误 */
2、test.cpp
#include <stdio.h>
#include <ctype.h>
#include "prio.h"
#include "seqstack.h"
int Priority(char opera, bool InStack)
{
int prio = OPERA_PRIO_ERR;
if(InStack)
{
switch(opera)
{
case '+':
prio = OPERA_PRIO_PLUS_IN;
break;
case '-':
prio = OPERA_PRIO_MINUS_IN;
break;
case '*':
prio = OPERA_PRIO_MULTIPLY_IN;
break;
case '/':
prio = OPERA_PRIO_DIVISION_IN;
break;
case '(':
prio = OPERA_PRIO_LEFT_BRACKETS_IN;
break;
default:
prio = OPERA_PRIO_ERR;
break;
}
}
else
{
switch(opera)
{
case '+':
prio = OPERA_PRIO_PLUS_OUT;
break;
case '-':
prio = OPERA_PRIO_MINUS_OUT;
break;
case '*':
prio = OPERA_PRIO_MULTIPLY_OUT;
break;
case '/':
prio = OPERA_PRIO_DIVISION_OUT;
break;
case '(':
prio = OPERA_PRIO_LEFT_BRACKETS_OUT;
break;
case ')':
prio = OPERA_PRIO_RIGHT_BRACKETS_OUT;
break;
default:
prio = OPERA_PRIO_ERR;
break;
}
}
return prio;
}
//栈的应用:将中序(缀)表达式改成后序(缀)表达式
void MidToLast(char *last,const char *mid)
{
Stack s;
InitStack(&s);
int prioOut;//栈外符号优先级
int prioIn;//栈内符号优先级
int ch;
while(*mid != '\0')//遍历中序表达式
{
if(isdigit(*mid))
{
*last++ = *mid++;
}
else if(IsEmpty(&s))//栈空,栈外符号直接进栈
{
Push(&s,*mid++);
}
else //需要比较符号优先级
{
GetTop(&s,&ch);
prioOut = Priority(*mid,false);
prioIn = Priority((char)ch,true);
if(prioIn < prioOut)//栈内优先级高,出栈
{
Pop(&s,&ch);
*last++ = (char)ch;
}
else if(prioIn > prioOut)//入栈
{
Push(&s,*mid++);
}
else//小括号匹配,直接删除
{
mid++;
Pop(&s,&ch);
}
}
}
while(!IsEmpty(&s))
{
Pop(&s,&ch);
*last++ = (char)ch;
}
*last = '\0';
}
int main()
{
char *mid = "3+4-2+3*2-6*(4-2)";
char last[100];
MidToLast(last,mid);
printf("%s\n%s\n",mid,last);
return 0;
}
上面程序的运行结果为:
顺序栈的实现在前面的博客中有写到,请自行查看博客《不定长顺序栈》