Algorithm:
- Tokenize the expression depending on the delemeter.
- Perform the following operations on each token.
- If token is operand, push the token to the stack
- If token is operator.
- Do two pops on stack. First one being operand 2 and second one being operand 1.
- Create an expression operand 1 + token + operand 2 and evaluate.
- Push the result in stack again.
- Pop the stack for the result.
Time Complexity : O(N)
Algorithm Execution:
Input Expression : 1 2 3 * +
Step 1 : Stack[1]
Step 3 : Stack[1, 2]
Step 4 : Stack[1,2,3]
Step 5 : Stack[1,6]
Step 5 : Stack[7] - Result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public String evalPostFix(String input, String delemeter){ | |
Stack<String> stack = new Stack<String>(input.length()); | |
StringBuffer sf = null; | |
StringTokenizer st = new StringTokenizer(input, delemeter); | |
String token = null; | |
String operand1, operand2; | |
while (st.hasMoreTokens()) { | |
token = st.nextToken(); | |
if(isOperand(token)){ | |
stack.push(token); | |
}else{ | |
sf = new StringBuffer(); | |
operand2 = stack.pop(); | |
operand1 = stack.pop(); | |
sf.append(operand1); | |
sf.append(token); | |
sf.append(operand2); | |
stack.push(evaluateExpression(sf.toString())+""); | |
} | |
} | |
return stack.pop(); | |
} |
0 comments:
Post a Comment