Skip to content

Instantly share code, notes, and snippets.

@dineshrajpurohit
Last active August 29, 2015 14:05
Show Gist options
  • Save dineshrajpurohit/3730c63619a828f47c52 to your computer and use it in GitHub Desktop.
Save dineshrajpurohit/3730c63619a828f47c52 to your computer and use it in GitHub Desktop.
Executing Postfix expression implementation using Javascript
/**
*
* Postfix implementation using StackList:
* Code for stacklist: https://gist.github.com/dineshrajpurohit/0bb67d29a039f85f2f10
*
* Dinesh
*
* PostFix Expression parsing and getting the result
*
* e.g: 42+351-*+ ==> 18
*
* Postfix parsing is implemented using Stacks
* Algorithm:
* - Whenever Integer come in from an expression add it to stack
* - Whenever and operator comes in from the expression add remove the top
* 2 Integer from the stack and operate on them using the operator
* - Repeat this until the entire expression is done
* - Print the stack item
*
**/
EX.PostFix = function(expression){
this.expression = expression;
var numStack = new EX.LinkedStack();
for(var i=0; i<expression.length; i++){
c = expression.charAt(i);
if(!isNaN(parseInt(c))){
numStack.pushToStack(parseInt(c));
}else if(c === '+' || c === '-' || c==='*' || c==='/' || c==='^'){
this.constructor.operate(numStack, c);
}
}
this.getResult = function(){
return numStack.stackTop().
}
}
// Static method to add the Integer based on the opration
EX.PostFix.operate = function(obj, operator){
var operand2 = obj.popFromStack().item;
var operand1 = obj.popFromStack().item;
switch(operator){
case "+":
obj.pushToStack(operand1+operand2);
break;
case "-":
obj.pushToStack(operand1-operand2);
break;
case "*":
obj.pushToStack(operand1*operand2);
break;
case "/":
obj.pushToStack(parseInt(operand1/operand2));
break;
case "^":
obj.pushToStack(Math.pow(operand1, operand2));
break;
}
}
console.log(" POSTFIX 42+351-");
var pfix = new EX.PostFix("42+351-*+");
console.log("Result for Expression: " + pfix.getResult());
/**
* OUT PUT
*
* POSTFIX 42+351- expressions_parsing.js:167
* Result for Expression: 18
*
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment