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.
Implementation:
C++
#include <bits/stdc++.h>
using namespace std;
bool isOperand( char c)
{
return isdigit (c);
}
double evaluatePrefix(string exprsn)
{
stack< double > Stack;
for ( int j = exprsn.size() - 1; j >= 0; j--) {
if (isOperand(exprsn[j]))
Stack.push(exprsn[j] - '0' );
else {
double o1 = Stack.top();
Stack.pop();
double o2 = Stack.top();
Stack.pop();
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();
}
int main()
{
string exprsn = "+9*26" ;
cout << evaluatePrefix(exprsn) << endl;
return 0;
}
|
Java
import java.io.*;
import java.util.*;
class GFG {
static Boolean isOperand( char c)
{
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--) {
if (isOperand(exprsn.charAt(j)))
Stack.push(( double )(exprsn.charAt(j) - 48 ));
else {
double o1 = Stack.peek();
Stack.pop();
double o2 = Stack.peek();
Stack.pop();
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();
}
public static void main(String[] args)
{
String exprsn = "+9*26" ;
System.out.println(evaluatePrefix(exprsn));
}
}
|
Python3
def is_operand(c):
return c.isdigit()
def evaluate(expression):
stack = []
for c in expression[:: - 1 ]:
if is_operand(c):
stack.append( int (c))
else :
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()
if __name__ = = "__main__" :
test_expression = "+9*26"
print (evaluate(test_expression))
|
C#
using System;
using System.Collections.Generic;
class GFG {
static Boolean isOperand( char c)
{
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--) {
if (isOperand(exprsn[j]))
Stack.Push(( double )(exprsn[j] - 48));
else {
double o1 = Stack.Peek();
Stack.Pop();
double o2 = Stack.Peek();
Stack.Pop();
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();
}
public static void Main(String[] args)
{
String exprsn = "+9*26" ;
Console.WriteLine(evaluatePrefix(exprsn));
}
}
|
Javascript
<script>
function isOperand(c)
{
if (c.charCodeAt() >= 48 && c.charCodeAt() <= 57)
return true ;
else
return false ;
}
function evaluatePrefix(exprsn)
{
let Stack = [];
for (let j = exprsn.length - 1; j >= 0; j--) {
if (isOperand(exprsn[j]))
Stack.push((exprsn[j].charCodeAt() - 48));
else {
let o1 = Stack[Stack.length - 1];
Stack.pop();
let o2 = Stack[Stack.length - 1];
Stack.pop();
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[Stack.length - 1];
}
let exprsn = "+9*26" ;
document.write(evaluatePrefix(exprsn));
</script>
|
Time Complexity: O(N)
Auxiliary Space: O(N)
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.
Below given is the extended program which allows operands to have multiple digits.
C++
#include <bits/stdc++.h>
using namespace std;
double evaluatePrefix(string exprsn)
{
stack< double > Stack;
for ( int j = exprsn.size() - 1; j >= 0; j--) {
if (exprsn[j] == ' ' )
continue ;
if ( isdigit (exprsn[j])) {
double num = 0, i = j;
while (j < exprsn.size() && isdigit (exprsn[j]))
j--;
j++;
for ( int k = j; k <= i; k++)
num = num * 10 + double (exprsn[k] - '0' );
Stack.push(num);
}
else {
double o1 = Stack.top();
Stack.pop();
double o2 = Stack.top();
Stack.pop();
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();
}
int main()
{
string exprsn = "+ 9 * 12 6" ;
cout << evaluatePrefix(exprsn) << endl;
return 0;
}
|
Java
import java.util.*;
public class Main
{
static boolean isdigit( char ch)
{
if (ch >= 48 && ch <= 57 )
{
return true ;
}
return false ;
}
static double evaluatePrefix(String exprsn)
{
Stack<Double> stack = new Stack<Double>();
for ( int j = exprsn.length() - 1 ; j >= 0 ; j--) {
if (exprsn.charAt(j) == ' ' )
continue ;
if (isdigit(exprsn.charAt(j))) {
double num = 0 , i = j;
while (j < exprsn.length() && isdigit(exprsn.charAt(j)))
j--;
j++;
for ( int k = j; k <= i; k++)
{
num = num * 10 + ( double )(exprsn.charAt(k) - '0' );
}
stack.push(num);
}
else {
double o1 = ( double )stack.peek();
stack.pop();
double o2 = ( double )stack.peek();
stack.pop();
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();
}
public static void main(String[] args) {
String exprsn = "+ 9 * 12 6" ;
System.out.print(( int )evaluatePrefix(exprsn));
}
}
|
Python3
def isdigit(ch):
if ( ord (ch) > = 48 and ord (ch) < = 57 ):
return True
return False
def evaluatePrefix(exprsn):
Stack = []
for j in range ( len (exprsn) - 1 , - 1 , - 1 ):
if (exprsn[j] = = ' ' ):
continue
if (isdigit(exprsn[j])):
num, i = 0 , j
while (j < len (exprsn) and isdigit(exprsn[j])):
j - = 1
j + = 1
for k in range (j, i + 1 , 1 ):
num = num * 10 + ( ord (exprsn[k]) - ord ( '0' ))
Stack.append(num)
else :
o1 = Stack[ - 1 ]
Stack.pop()
o2 = Stack[ - 1 ]
Stack.pop()
if exprsn[j] = = '+' :
Stack.append(o1 + o2 + 12 )
elif exprsn[j] = = '-' :
Stack.append(o1 - o2)
elif exprsn[j] = = '*' :
Stack.append(o1 * o2 * 5 )
elif exprsn[j] = = '/' :
Stack.append(o1 / o2)
return Stack[ - 1 ]
exprsn = "+ 9 * 12 6"
print (evaluatePrefix(exprsn))
|
C#
using System;
using System.Collections;
class GFG {
static bool isdigit( char ch)
{
if (ch >= 48 && ch <= 57)
{
return true ;
}
return false ;
}
static double evaluatePrefix( string exprsn)
{
Stack stack = new Stack();
for ( int j = exprsn.Length - 1; j >= 0; j--) {
if (exprsn[j] == ' ' )
continue ;
if (isdigit(exprsn[j])) {
double num = 0, i = j;
while (j < exprsn.Length && isdigit(exprsn[j]))
j--;
j++;
for ( int k = j; k <= i; k++)
{
num = num * 10 + ( double )(exprsn[k] - '0' );
}
stack.Push(num);
}
else {
double o1 = ( double )stack.Peek();
stack.Pop();
double o2 = ( double )stack.Peek();
stack.Pop();
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 ( double )stack.Peek();
}
static void Main() {
string exprsn = "+ 9 * 12 6" ;
Console.Write(evaluatePrefix(exprsn));
}
}
|
Javascript
<script>
function isdigit(ch)
{
if (ch.charCodeAt() >= 48 && ch.charCodeAt() <= 57)
{
return true ;
}
return false ;
}
function evaluatePrefix(exprsn)
{
let Stack = [];
for (let j = exprsn.length - 1; j >= 0; j--) {
if (exprsn[j] == ' ' )
continue ;
if (isdigit(exprsn[j])) {
let num = 0, i = j;
while (j < exprsn.length && isdigit(exprsn[j]))
j--;
j++;
for (let k = j; k <= i; k++)
num = num * 10 + (exprsn[k].charCodeAt() - '0' .charCodeAt());
Stack.push(num);
}
else {
let o1 = Stack[Stack.length - 1];
Stack.pop();
let o2 = Stack[Stack.length - 1];
Stack.pop();
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[Stack.length - 1];
}
let exprsn = "+ 9 * 12 6" ;
document.write(evaluatePrefix(exprsn));
</script>
|
Time Complexity: O(n)
Auxiliary Space: O(n)
Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
12 Jan, 2023
Like Article
Save Article