java+infix_在将infix表达式转换为后缀表达式时处理括号

在将infix表达式转换为后缀表达式时处理括号

我正在使用Java开发一个项目,该项目要求我将infix表达式转换为后缀表达式。我目前能够使用此方法将infix表达式转换为后缀,只要它们不包含括号,但我不知道如何处理括号。

基本上,我有两个堆栈,它们保存被称为“令牌”的对象。令牌是一个包装类,它包含一个字符串,该字符串要么是数字、变量(在用户输入时被计算为数字,待定)、运算符(运算符具有与其关联的优先级级别,以便使我的方法可以确定如何处理‘+’、‘-’、‘*’和‘/’之间的操作顺序,要么是括号(括号有确定它是开括号还是关闭括号)的方法。

我该如何处理括号?多层括号呢?public String toPostFix() {

StringBuilder postfixstr = new StringBuilder();

Stack in_fix = new Stack<>();

Stack post_fix = new Stack<>();

for (int i = tokens.length - 1; i >= 0; i--) {

t = new Token(tokens[i]);

in_fix.push(t);

}

//there are still tokens to process

while (!in_fix.empty()) {

//is a number

if (in_fix.peek().type == 1) {

postfixstr.append(in_fix.pop().toString());

}

//is an operator and the stack is empty

else if (in_fix.peek().type == 3 && post_fix.empty()) {

post_fix.push(in_fix.pop());

}

// is an operator that has higher priority than the operator on the stack

else if (in_fix.peek().type == 3 && in_fix.peek().isOperator() > post_fix.peek().isOperator()) {

post_fix.push(in_fix.pop());

}

// is an operator that has lower priority than the operator on the stack

else if (in_fix.peek().type == 3 && in_fix.peek().isOperator() <= post_fix.peek().isOperator()) {

postfixstr.append(post_fix.pop());

post_fix.push(in_fix.pop());

}

//puts the rest of the stack onto the output string

if (in_fix.empty()) {

while (!post_fix.empty()) {

postfixstr.append(post_fix.pop());

}

}

}

return postfixstr.toString();}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值