中缀转前缀表达式过程Java,中缀表达式转为前缀表达式,该怎么处理

当前位置:我的异常网» Java面试 » 中缀表达式转为前缀表达式,该怎么处理

中缀表达式转为前缀表达式,该怎么处理

www.myexceptions.net  网友分享于:2013-01-15  浏览:26次

中缀表达式转为前缀表达式

举例

3 输出 3

1 + 1 输出 (+ 1 1)

2 * 5 + 1 输出 (+ 1 (* 2 5))

2 * ( 5 + 1 ) 输出 (* (+ 1 5) 2)

3 * x + ( 9 + y ) / 4 输出 (+ (* 3 x) (/ (+ 9 y) 4))

这是我现有的代码:

#include

#include

using namespace std;

#define maxSize 100

class Stack{

public:

Stack() {top = -1 ; };

bool Push(char a)

{

if(!IsFull())

c[++top] = a;

else

return false;

return true;

}

bool pop(char &a)

{

if(!IsEmpty())

a = c[top--];

else

return false;

return true;

}

bool getTop(char &a)

{

if(!IsEmpty())

a = c[top];

else

return false;

return true;

}

bool IsEmpty()

{

return top == -1 ? true:false ;

}

bool IsFull()

{

return top == (maxSize-1) ? true:false ;

}

private:

char c[maxSize];

int top;

};

int string_length(string s)

{

int n;

for(n=0 ; s[n]!='\0' ; n++); //O(n)

n--;

return n;

}

int priority1(char a) //O(1)

{

if(a == '#')

return 0;

if(a == '(')

return 6;

if(a == '*' || a == '/')

return 4;

if(a == '+' || a == '-')

return 2;

if(a == ')')

return 1;

return false;

}

int priority2(char a)

{

if(a == '#')

return 0;

if(a == '(')

return 1;

if(a == '*' || a == '/')

return 5;

if(a == '+' || a == '-')

return 3;

if(a == ')')

return 6;

return false;

}

char pre_operator(string s, int n)

{

while(s[n] >= '0' && s[n] <= '9' || s[n] =='.')

pre_operator(s, --n);

return s[n];

}

int main()

{

string s;

char c[100];

char a,b;

cout<

cin>>s;

s = "#"+s;

int m = 0,n;

n = string_length(s);

Stack z;

z.Push('#');

while(n >= 0 && !z.IsEmpty()) //O(n*n)

{

if(isdigit(s[n]))

{//cout<

z.getTop(a);

if(priority2(pre_operator(s, n)) >= priority1(a)) //O(n)

// if the priority2 of operator right before the s[n] is >= top character in stack,

//we need ')' here

{c[m++] = ')';cout<

while(s[n] >= '0' && s[n] <= '9' || s[n] =='.')

c[m++] = s[n--];

c[m++] = ' ';

}

else

{

z.getTop(a);

if(priority1(a) < priority2(s[n]))

{

z.Push(s[n--]);

z.getTop(a);

}

else if(priority1(a) > priority2(s[n]))

z.pop(b) , c[m++] = b;

else

{

z.pop(b);

if(b == ')')

n--;

}

}

}

m--;

cout<

for( ; m >=0 ; n++,m--) //O(n)

if(c[m] == '+' || c[m] == '-' || c[m] == '*' || c[m] == '/')

cout<

else

cout<

cout<

return 0;

}

问题是 输出的右括号不正确,输入是2+3*2, 输出是 (+ 2(* 3 2)

文章评论

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值