中缀式转后缀式工具类实现 (六)

2014-11-24 11:03:48 · 作者: · 浏览: 5
ent != Operators.OPEN_BRACKET)
{
addCharToResult(operators.pop());
lastElement = operators.lastElement();
}

// 最后再弹出'('
operators.pop();
}

/**
*
*

* 待入栈元素优先级是否不高于栈顶元素,栈为空时,为高于
*
* @param ch
* @return
*

*/
private static boolean isLowerThanTop(char ch)
{
// 操作符栈为空或为'('时,操作符需要直接入栈
if (operators.isEmpty() || operators.lastElement() == Operators.OPEN_BRACKET)
{
return false;
}
char topChar = operators.lastElement();
return OperatorUtils.isLowerOfPriority(ch, topChar);
}

/**
*

* 当待入栈的操作符优先级不高于栈顶时,栈顶元素出栈,直至栈顶元素低于待入栈元素,然后再把待入栈元素入栈
*
* @param ch
*

*/
private static void popUntilLowerTop(char ch)
{
while (isLowerThanTop(ch))
{
addCharToResult(operators.pop());
}
operators.push(ch);
}

/**
*
*

* 把解析好的字符加入输出结果中
*
* @param ch
*

*/
private static void addCharToResult(char ch)
{
// 结果不为空时,同时不连续为非操作符时,加空格后再加字符
if (OperatorUtils.isOperator(ch) || OperatorUtils.isOperator(lastElement))
{
result.append(Operators.SPACE);
}
result.append(ch);
}

/**
*

* 表达式解析完毕,依次从栈顶弹出操作符
*
*

*/
private static void popAllOperators()
{
while (!operators.isEmpty())
{
addCharToResult(operators.pop());
}
}
}
单元测试类:


[java] import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
*


* <一句话功能简述>
*
*

*/
public class SuffixExpressionUtilsTest
{
@Test
public void testGetSuffixExp01()
{
assertEquals(SuffixExpressionUtils.getSuffixExp(null), null);
}

@Test
public void testGetSuffixExp02()
{
String result = SuffixExpressionUtils.getSuffixExp("1+2*3");
assertEquals(result, "1 2 3 * +");
}

@Test
public void testGetSuffixExp02_1()
{
String result = SuffixExpressionUtils.getSuffixExp("1*2-3");
assertEquals(result, "1 2 * 3 -");
}

@Test
public void testGetSuffixExp03()
{
String result = SuffixExpressionUtils.getSuffixExp("(7-(1+2)/5)*3+8");
assertEquals(result, "7 1 2 + 5 / - 3 * 8 +");
}

@Test
public void testGetSuffixExp04()
{
String result = SuffixExpressionUtils.getSuffixExp("(70-(11+22)/55)*63+897");
assertEquals(result, "70 11 22 + 55 / - 63 * 897 +");
}

@Test
public void testGetSuffixExp05()
{
String result = SuffixExpressionUtils.getSuffixExp("{[70-(11+22)]/55}*63+897");
assertEquals(result, "70 11 22 + - 55 / 63 * 897 +");
}

@Test
public void testGetSuffixExp06()
{
String result = SuffixExpressionUtils.getSuffixExp("{[70-(a+22)]/c}*63+897");
assertEquals(result, "70 a 22 + - c / 63 * 897 +");
}
}

import static org.junit.Assert.assertEquals;

import org.junit.Test;

/**
*


* <一句话功能简述>
*
*

*/
public class SuffixExpressionUtilsTest
{
@Test
public void testGetSuffixExp01()
{
assertEquals(SuffixExpressionUtils.getSuffixExp(null), null);
}

@Test
public void testGetSuffixExp02()
{
String result = SuffixExpressionU