Prefix and Postfix expressions can be evaluated faster than an infix expression. This is because we don’t need to process any brackets or follow operator precedence rule. In postfix and prefix expressions which ever operator comes before will be evaluated first, irrespective of its priority. Also, there are no brackets in these expressions. As long as we can guarantee that a valid prefix or postfix expression is used, it can be evaluated with correctness.
We can convert infix to postfix and can convert infix to prefix.
In this article, we will discuss how to evaluate an expression written in prefix notation. The method is similar to evaluating a postfix expression. Please read Evaluation of Postfix Expression to know how to evaluate postfix expressions
Algorithm
EVALUATE_PREFIX(STRING) Step 1: Put a pointer P at the end of the end Step 2: If character at P is an operand push it to Stack Step 3: If the character at P is an operator pop two elements from the Stack. Operate on these elements according to the operator, and push the result back to the Stack Step 4: Decrement P by 1 and go to Step 2 as long as there are characters left to be scanned in the expression. Step 5: The Result is stored at the top of the Stack, return it Step 6: End
Example to demonstrate working of the algorithm
Expression: +9*26 Character | Stack | Explanation Scanned | (Front to | | Back) | ------------------------------------------- 6 6 6 is an operand, push to Stack 2 6 2 2 is an operand, push to Stack * 12 (6*2) * is an operator, pop 6 and 2, multiply them and push result to Stack 9 12 9 9 is an operand, push to Stack + 21 (12+9) + is an operator, pop 12 and 9 add them and push result to Stack Result: 21
Examples:
Input : -+8/632 Output : 8 Input : -+7*45+20 Output : 25
Complexity The algorithm has linear complexity since we scan the expression once and perform at most O(N) push and pop operations which take constant time.
Implementation of the algorithm is given below.
C++
// C++ program to evaluate a prefix expression. #include <bits/stdc++.h> using namespace std; bool isOperand( char c) { // If the character is a digit then it must // be an operand return isdigit (c); } double evaluatePrefix(string exprsn) { stack< double > Stack; for ( int j = exprsn.size() - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.push(exprsn[j] - '0' ); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.top(); Stack.pop(); double o2 = Stack.top(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+' : Stack.push(o1 + o2); break ; case '-' : Stack.push(o1 - o2); break ; case '*' : Stack.push(o1 * o2); break ; case '/' : Stack.push(o1 / o2); break ; } } } return Stack.top(); } // Driver code int main() { string exprsn = "+9*26" ; cout << evaluatePrefix(exprsn) << endl; return 0; } |
Java
// Java program to evaluate // a prefix expression. import java.io.*; import java.util.*; class GFG { static Boolean isOperand( char c) { // If the character is a digit // then it must be an operand if (c >= 48 && c <= 57 ) return true ; else return false ; } static double evaluatePrefix(String exprsn) { Stack<Double> Stack = new Stack<Double>(); for ( int j = exprsn.length() - 1 ; j >= 0 ; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn.charAt(j))) Stack.push(( double )(exprsn.charAt(j) - 48 )); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.peek(); Stack.pop(); double o2 = Stack.peek(); Stack.pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn.charAt(j)) { case '+' : Stack.push(o1 + o2); break ; case '-' : Stack.push(o1 - o2); break ; case '*' : Stack.push(o1 * o2); break ; case '/' : Stack.push(o1 / o2); break ; } } } return Stack.peek(); } /* Driver program to test above function */ public static void main(String[] args) { String exprsn = "+9*26" ; System.out.println(evaluatePrefix(exprsn)); } } // This code is contributed by Gitanjali |
Python3
""" Python3 program to evaluate a prefix expression. """ def is_operand(c): """ Return True if the given char c is an operand, e.g. it is a number """ return c.isdigit() def evaluate(expression): """ Evaluate a given expression in prefix notation. Asserts that the given expression is valid. """ stack = [] # iterate over the string in reverse order for c in expression[:: - 1 ]: # push operand to stack if is_operand(c): stack.append( int (c)) else : # pop values from stack can calculate the result # push the result onto the stack again o1 = stack.pop() o2 = stack.pop() if c = = '+' : stack.append(o1 + o2) elif c = = '-' : stack.append(o1 - o2) elif c = = '*' : stack.append(o1 * o2) elif c = = '/' : stack.append(o1 / o2) return stack.pop() # Driver code if __name__ = = "__main__" : test_expression = "+9*26" print (evaluate(test_expression)) # This code is contributed by Leon Morten Richter (GitHub: M0r13n) |
C#
// C# program to evaluate // a prefix expression. using System; using System.Collections.Generic; class GFG { static Boolean isOperand( char c) { // If the character is a digit // then it must be an operand if (c >= 48 && c <= 57) return true ; else return false ; } static double evaluatePrefix(String exprsn) { Stack<Double> Stack = new Stack<Double>(); for ( int j = exprsn.Length - 1; j >= 0; j--) { // Push operand to Stack // To convert exprsn[j] to digit subtract // '0' from exprsn[j]. if (isOperand(exprsn[j])) Stack.Push(( double )(exprsn[j] - 48)); else { // Operator encountered // Pop two elements from Stack double o1 = Stack.Peek(); Stack.Pop(); double o2 = Stack.Peek(); Stack.Pop(); // Use switch case to operate on o1 // and o2 and perform o1 O o2. switch (exprsn[j]) { case '+' : Stack.Push(o1 + o2); break ; case '-' : Stack.Push(o1 - o2); break ; case '*' : Stack.Push(o1 * o2); break ; case '/' : Stack.Push(o1 / o2); break ; } } } return Stack.Peek(); } /* Driver code */ public static void Main(String[] args) { String exprsn = "+9*26" ; Console.WriteLine(evaluatePrefix(exprsn)); } } /* This code contributed by PrinciRaj1992 */ |
Output:
21
Note:
To perform more types of operations only the switch case table needs to be modified. This implementation works only for single digit operands. Multi-digit operands can be implemented if some character like space is used to separate the operands and operators.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.