最近自己在看数据结构,作为菜鸟,试着写了些“代码”。关于前缀、中缀、后缀表达式的含义,我就在这不啰嗦了。直接转化吧,先看看中转后。。。 ps:在实现过程中,我用的是栈的结构,栈的实现在另一篇文章中会提到。。
#include <stdio.h>
#include <ctype.h>
#include "mid_to_last_stack.h"
#define IN_ADD 4
#define IN_SUB 4
#define IN_MOV 6
#define IN_DIV 6
#define IN_LEFT 2
#define IN_RIGHT 0
#define OUT_ADD 3
#define OUT_SUB 3
#define OUT_MOV 5
#define OUT_DIV 5
#define OUT_LEFT 10
#define OUT_RIGHT 2
#define IN_OUT_ERROR 0
typedef enum exp_Statue
{
IN,OUT
}Statue;
int get_level(char sign,Statue status)
{
if (status==IN)
{
switch(sign)
{
case '+':
return IN_ADD;
case '-':
return IN_SUB;
case '*':
return IN_MOV;
case '/':
return IN_DIV;
case '(':
return IN_LEFT;
case ')':
return IN_RIGHT;
default:
break;
}
}
else
{
switch(sign)
{
case '+':
return OUT_ADD;
case '-':
return OUT_SUB;
case '*':
return OUT_MOV;
case '/':
return OUT_DIV;
case '(':
return OUT_LEFT;
case ')':
return OUT_RIGHT;
default:
break;
}
}
return IN_OUT_ERROR;
}
void mid_to_last(char *mid,char *last)
{
dseq_stack s;
init_stack(&s);
char tmp;
int level1=0;
int level2=0;
while(*mid)
{
if (isdigit(*mid))
{
*last++=*mid++;
*last++ = ' ';
}
else
{
if (is_empty(&s))
{
push_stack(&s,*mid);
mid++;
}
else
{
get_top(&s,&tmp);
level1=get_level(*mid,OUT);
level2=get_level(tmp,IN);
if (level1>level2)
{
push_stack(&s,*mid);
mid++;
}
else if (level1<level2)
{
pop_stack(&s, last);
last++;
}
else
{
pop_stack(&s,&tmp);
mid++;
}
}
}
}
while (!is_empty(&s))
{
pop_stack(&s,last);
last++;
}
*last = '\0';
}
int main()
{
char *mid_exp="4+3*5-2*3";
char last_exp[50]="";
mid_to_last(mid_exp,last_exp);
printf("%s\n",last_exp);
return 0;
}