Skip to content

Instantly share code, notes, and snippets.

@cookfront
Last active August 29, 2015 13:57
Show Gist options
  • Save cookfront/9889519 to your computer and use it in GitHub Desktop.
Save cookfront/9889519 to your computer and use it in GitHub Desktop.
/**
* 中缀表达式转后缀表达式
*/
function isOperator (item) {
return item === '+' || item === '-' || item === '*' || item === '/' || item === '(' || item === ')';
}
function convert (str) {
var output = [],
stack = [],
operator;
for (var i = 0, len = str.length; i < len; i++) {
var item = str.charAt(i);
// 非运算符直接输出
if (!isOperator(item)) {
if (item == ' ') {
continue;
}
output.push(item);
} else {
switch (item) {
// 加法和减法运算符会将栈中的+-*/运算符出栈并输出
case '+':
case '-':
while (stack[0] === '+' || stack[0] === '-' || stack[0] === '*' || stack[0] === '/') {
output.push(stack.shift());
}
stack.unshift(item);
break;
// 乘法和除法运算符将栈中的*/运算符出栈并输出
case '*':
case '/':
while (stack[0] === '*' || stack[0] === '/') {
output.push(stack.shift());
}
stack.unshift(item);
break;
// (运算符优先级最高,因为没有比它优先级低的运算符,直接入栈
case '(':
stack.unshift(item);
break;
// 当遇到右括号,将左括号之前的元素全部输出
case ')':
while ((operator = stack.shift())) {
if (operator != '(') {
output.push(operator);
} else {
break;
}
}
}
}
}
while (stack.length != 0) {
output.push(stack.shift());
}
return output.join('');
}
console.log(convert('( a + (b*c))+(((d*e)+f)*g)'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment