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
You can fork the source code and unit tests from github.
0 comments:
Post a Comment