Stack | Set 4 (Evaluation of Postfix Expression) - GeeksforGeeks

14 Jan, 2022
The Postfix notation is used to represent algebraic expressions. The expressions written in postfix form are evaluated faster compared to infix notation as parenthesis are not required in postfix. We have discussed infix to postfix conversion. In this post, evaluation of postfix expressions is discussed.
Following is an algorithm for evaluation postfix expressions. 1) Create a stack to store operands (or values). 2) Scan the given expression and do the following for every scanned element. .....a) If the element is a number, push it into the stack .....b) If the element is an operator, pop operands for the operator from the stack. Evaluate the operator and push the result back to the stack 3) When the expression is ended, the number in the stack is the final answer 
Example: Let the given expression be “2 3 1 * + 9 -“. We scan all elements one by one. 1) Scan ‘2’, it’s a number, so push it to stack. Stack contains ‘2’ 2) Scan ‘3’, again a number, push it to stack, stack now contains ‘2 3’ (from bottom to top) 3) Scan ‘1’, again a number, push it to stack, stack now contains ‘2 3 1’ 4) Scan ‘*’, it’s an operator, pop two operands from stack, apply the * operator on operands, we get 3*1 which results in 3. We push the result ‘3’ to stack. The stack now becomes ‘2 3’. 5) Scan ‘+’, it’s an operator, pop two operands from stack, apply the + operator on operands, we get 3 + 2 which results in 5. We push the result ‘5’ to stack. The stack now becomes ‘5’. 6) Scan ‘9’, it’s a number, we push it to the stack. The stack now becomes ‘5 9’. 7) Scan ‘-‘, it’s an operator, pop two operands from stack, apply the – operator on operands, we get 5 – 9 which results in -4. We push the result ‘-4’ to the stack. The stack now becomes ‘-4’. 8) There are no more elements to scan, we return the top element from the stack (which is the only element left in a stack).
Below is the implementation of the above algorithm. 
C++
C
Java
Python3
C#
Javascript
// C++ program to evaluate value of a postfix expression#include <iostream>#include <string.h> using namespace std; // Stack typestruct Stack{    int top;    unsigned capacity;    int* array;}; // Stack Operationsstruct Stack* createStack( unsigned capacity ){    struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));     if (!stack) return NULL;     stack->top = -1;    stack->capacity = capacity;    stack->array = (int*) malloc(stack->capacity * sizeof(int));     if (!stack->array) return NULL;     return stack;} int isEmpty(struct Stack* stack){    return stack->top == -1 ;} char peek(struct Stack* stack){    return stack->array[stack->top];} char pop(struct Stack* stack){    if (!isEmpty(stack))        return stack->array[stack->top--] ;    return '$';} void push(struct Stack* stack, char op){    stack->array[++stack->top] = op;}  // The main function that returns value of a given postfix expressionint evaluatePostfix(char* exp){    // Create a stack of capacity equal to expression size    struct Stack* stack = createStack(strlen(exp));    int i;     // See if stack was created successfully    if (!stack) return -1;     // Scan all characters one by one    for (i = 0; exp[i]; ++i)    {        // If the scanned character is an operand (number here),        // push it to the stack.        if (isdigit(exp[i]))            push(stack, exp[i] - '0');         // If the scanned character is an operator, pop two        // elements from stack apply the operator        else        {            int val1 = pop(stack);            int val2 = pop(stack);            switch (exp[i])            {            case '+': push(stack, val2 + val1); break;            case '-': push(stack, val2 - val1); break;            case '*': push(stack, val2 * val1); break;            case '/': push(stack, val2/val1); break;            }        }    }    return pop(stack);} // Driver program to test above functionsint main(){    char exp[] = "231*+9-";    cout<<"postfix evaluation: "<< evaluatePostfix(exp);    return 0;}
// C program to evaluate value of a postfix expression#include <stdio.h>#include <string.h>#include <ctype.h>#include <stdlib.h> // Stack typestruct Stack{    int top;    unsigned capacity;    int* array;}; // Stack Operationsstruct Stack* createStack( unsigned capacity ){    struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));     if (!stack) return NULL;     stack->top = -1;    stack->capacity = capacity;    stack->array = (int*) malloc(stack->capacity * sizeof(int));     if (!stack->array) return NULL;     return stack;} int isEmpty(struct Stack* stack){    return stack->top == -1 ;} char peek(struct Stack* stack){    return stack->array[stack->top];} char pop(struct Stack* stack){    if (!isEmpty(stack))        return stack->array[stack->top--] ;    return '$';} void push(struct Stack* stack, char op){    stack->array[++stack->top] = op;}  // The main function that returns value of a given postfix expressionint evaluatePostfix(char* exp){    // Create a stack of capacity equal to expression size    struct Stack* stack = createStack(strlen(exp));    int i;     // See if stack was created successfully    if (!stack) return -1;     // Scan all characters one by one    for (i = 0; exp[i]; ++i)    {        // If the scanned character is an operand (number here),        // push it to the stack.        if (isdigit(exp[i]))            push(stack, exp[i] - '0');         // If the scanned character is an operator, pop two        // elements from stack apply the operator        else        {            int val1 = pop(stack);            int val2 = pop(stack);            switch (exp[i])            {            case '+': push(stack, val2 + val1); break;            case '-': push(stack, val2 - val1); break;            case '*': push(stack, val2 * val1); break;            case '/': push(stack, val2/val1); break;            }        }    }    return pop(stack);} // Driver program to test above functionsint main(){    char exp[] = "231*+9-";    printf ("postfix evaluation: %d", evaluatePostfix(exp));    return 0;}
// Java program to evaluate value of a postfix expression import java.util.Stack; public class Test{    // Method to evaluate value of a postfix expression    static int evaluatePostfix(String exp)    {        //create a stack        Stack<Integer> stack=new Stack<>();                 // Scan all characters one by one        for(int i=0;i<exp.length();i++)        {            char c=exp.charAt(i);                         // If the scanned character is an operand (number here),            // push it to the stack.            if(Character.isDigit(c))            stack.push(c - '0');                         //  If the scanned character is an operator, pop two            // elements from stack apply the operator            else            {                int val1 = stack.pop();                int val2 = stack.pop();                                 switch(c)                {                    case '+':                    stack.push(val2+val1);                    break;                                         case '-':                    stack.push(val2- val1);                    break;                                         case '/':                    stack.push(val2/val1);                    break;                                         case '*':                    stack.push(val2*val1);                    break;              }            }        }        return stack.pop();       }         // Driver program to test above functions    public static void main(String[] args)    {        String exp="231*+9-";        System.out.println("postfix evaluation: "+evaluatePostfix(exp));    }}// Contributed by Sumit Ghosh
# Python program to evaluate value of a postfix expression # Class to convert the expressionclass Evaluate:         # Constructor to initialize the class variables    def __init__(self, capacity):        self.top = -1        self.capacity = capacity        # This array is used a stack        self.array = []         # check if the stack is empty    def isEmpty(self):        return True if self.top == -1 else False         # Return the value of the top of the stack    def peek(self):        return self.array[-1]         # Pop the element from the stack    def pop(self):        if not self.isEmpty():            self.top -= 1            return self.array.pop()        else:            return "$"         # Push the element to the stack    def push(self, op):        self.top += 1        self.array.append(op)      # The main function that converts given infix expression    # to postfix expression    def evaluatePostfix(self, exp):                 # Iterate over the expression for conversion        for i in exp:                         # If the scanned character is an operand            # (number here) push it to the stack            if i.isdigit():                self.push(i)             # If the scanned character is an operator,            # pop two elements from stack and apply it.            else:                val1 = self.pop()                val2 = self.pop()                self.push(str(eval(val2 + i + val1)))         return int(self.pop())                               # Driver program to test above functionexp = "231*+9-"obj = Evaluate(len(exp))print ("postfix evaluation: %d"%(obj.evaluatePostfix(exp)))# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// C# program to evaluate value of a postfix expressionusing System;using System.Collections; namespace GFG{    class Geek    {        //Main() method        static void Main()        {            Geek e = new Geek();            e.v = ("231*+9-");            e.expression();            Console.WriteLine("postfix evaluation: " + e.answer);            Console.Read();        }         public string v;        //'v' is variable to store the string value         public string answer;        Stack i = new Stack();        //'Stack()' is inbuilt function for namespace 'System.Collections'         public void expression()        //evaluation method        {            int a, b, ans;            for (int j = 0; j < v.Length; j++)            //'v.Length' means length of the string            {                String c = v.Substring(j, 1);                if (c.Equals("*"))                {                    String sa = (String)i.Pop();                    String sb = (String)i.Pop();                    a = Convert.ToInt32(sb);                    b = Convert.ToInt32(sa);                    ans = a * b;                    i.Push(ans.ToString());                 }                else if (c.Equals("/"))                {                    String sa = (String)i.Pop();                    String sb = (String)i.Pop();                    a = Convert.ToInt32(sb);                    b = Convert.ToInt32(sa);                    ans = a / b;                    i.Push(ans.ToString());                }                else if (c.Equals("+"))                {                    String sa = (String)i.Pop();                    String sb = (String)i.Pop();                    a = Convert.ToInt32(sb);                    b = Convert.ToInt32(sa);                    ans = a + b;                    i.Push(ans.ToString());                 }                else if (c.Equals("-"))                {                    String sa = (String)i.Pop();                    String sb = (String)i.Pop();                    a = Convert.ToInt32(sb);                    b = Convert.ToInt32(sa);                    ans = a - b;                    i.Push(ans.ToString());                 }                else                {                    i.Push(v.Substring(j, 1));                }            }            answer = (String)i.Pop();        }    }}
<script> // Javascript program to evaluate value of a postfix expression // Method to evaluate value of a postfix expressionfunction evaluatePostfix(exp){    //create a stack        let stack=[];                  // Scan all characters one by one        for(let i=0;i<exp.length;i++)        {            let c=exp[i];                          // If the scanned character is an operand (number here),            // push it to the stack.            if(! isNaN( parseInt(c) ))            stack.push(c.charCodeAt(0) - '0'.charCodeAt(0));                          //  If the scanned character is an operator, pop two            // elements from stack apply the operator            else            {                let val1 = stack.pop();                let val2 = stack.pop();                                  switch(c)                {                    case '+':                    stack.push(val2+val1);                    break;                                          case '-':                    stack.push(val2- val1);                    break;                                          case '/':                    stack.push(val2/val1);                    break;                                          case '*':                    stack.push(val2*val1);                    break;              }            }        }        return stack.pop();  } // Driver program to test above functionslet exp="231*+9-";document.write("postfix evaluation: "+evaluatePostfix(exp)); // This code is contributed by avanitrachhadiya2155</script>
Output: 
postfix evaluation: -4
The time complexity of the evaluation algorithm is O(n) where n is a number of characters in the input expression.
There are the following limitations of the above implementation. 1) It supports only 4 binary operators ‘+’, ‘*’, ‘-‘ and ‘/’. It can be extended for more operators by adding more switch cases. 2) The allowed operands are only single-digit operands. The program can be extended for multiple digits by adding a separator-like space between all elements (operators and operands) of the given expression.  
Below given is the extended program which allows operands to have multiple digits. 
C++
C
Java
Python3
C#
Javascript
// C++ program to evaluate value of a postfix// expression having multiple digit operands#include <bits/stdc++.h>using namespace std; // Stack typeclass Stack{    public:    int top;    unsigned capacity;    int* array;}; // Stack OperationsStack* createStack( unsigned capacity ){    Stack* stack = new Stack();     if (!stack) return NULL;     stack->top = -1;    stack->capacity = capacity;    stack->array = new int[(stack->capacity * sizeof(int))];     if (!stack->array) return NULL;     return stack;} int isEmpty(Stack* stack){    return stack->top == -1 ;} int peek(Stack* stack){    return stack->array[stack->top];} int pop(Stack* stack){    if (!isEmpty(stack))        return stack->array[stack->top--] ;    return '$';} void push(Stack* stack,int op){    stack->array[++stack->top] = op;}  // The main function that returns value// of a given postfix expressionint evaluatePostfix(char* exp){    // Create a stack of capacity equal to expression size    Stack* stack = createStack(strlen(exp));    int i;     // See if stack was created successfully    if (!stack) return -1;     // Scan all characters one by one    for (i = 0; exp[i]; ++i)    {        //if the character is blank space then continue        if(exp[i] == ' ')continue;                 // If the scanned character is an        // operand (number here),extract the full number        // Push it to the stack.        else if (isdigit(exp[i]))        {            int num=0;                         //extract full number            while(isdigit(exp[i]))            {            num = num * 10 + (int)(exp[i] - '0');                i++;            }            i--;                         //push the element in the stack            push(stack,num);        }                 // If the scanned character is an operator, pop two        // elements from stack apply the operator        else        {            int val1 = pop(stack);            int val2 = pop(stack);                         switch (exp[i])            {            case '+': push(stack, val2 + val1); break;            case '-': push(stack, val2 - val1); break;            case '*': push(stack, val2 * val1); break;            case '/': push(stack, val2/val1); break;                         }        }    }    return pop(stack);} // Driver codeint main(){    char exp[] = "100 200 + 2 / 5 * 7 +";    cout << evaluatePostfix(exp);    return 0;} // This code is contributed by rathbhupendra
// C program to evaluate value of a postfix// expression having multiple digit operands#include <stdio.h>#include <string.h>#include <ctype.h>#include <stdlib.h> // Stack typestruct Stack{    int top;    unsigned capacity;    int* array;}; // Stack Operationsstruct Stack* createStack( unsigned capacity ){    struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));     if (!stack) return NULL;     stack->top = -1;    stack->capacity = capacity;    stack->array = (int*) malloc(stack->capacity * sizeof(int));     if (!stack->array) return NULL;     return stack;} int isEmpty(struct Stack* stack){    return stack->top == -1 ;} int peek(struct Stack* stack){    return stack->array[stack->top];} int pop(struct Stack* stack){    if (!isEmpty(stack))        return stack->array[stack->top--] ;    return '$';} void push(struct Stack* stack,int op){    stack->array[++stack->top] = op;}  // The main function that returns value// of a given postfix expressionint evaluatePostfix(char* exp){    // Create a stack of capacity equal to expression size    struct Stack* stack = createStack(strlen(exp));    int i;     // See if stack was created successfully    if (!stack) return -1;     // Scan all characters one by one    for (i = 0; exp[i]; ++i)    {        //if the character is blank space then continue        if(exp[i]==' ')continue;                 // If the scanned character is an        // operand (number here),extract the full number        // Push it to the stack.        else if (isdigit(exp[i]))        {            int num=0;                         //extract full number            while(isdigit(exp[i]))            {            num=num*10 + (int)(exp[i]-'0');                i++;            }            i--;                         //push the element in the stack            push(stack,num);        }                 // If the scanned character is an operator, pop two        // elements from stack apply the operator        else        {            int val1 = pop(stack);            int val2 = pop(stack);                         switch (exp[i])            {            case '+': push(stack, val2 + val1); break;            case '-': push(stack, val2 - val1); break;            case '*': push(stack, val2 * val1); break;            case '/': push(stack, val2/val1); break;                         }        }    }    return pop(stack);} // Driver program to test above functionsint main(){    char exp[] = "100 200 + 2 / 5 * 7 +";    printf ("%d", evaluatePostfix(exp));    return 0;} // This code is contributed by Arnab Kundu
// Java program to evaluate value of a postfix// expression having multiple digit operandsimport java.util.Stack; class Test1{    // Method to evaluate value of a postfix expression    static int evaluatePostfix(String exp)    {        //create a stack        Stack<Integer> stack = new Stack<>();                 // Scan all characters one by one        for(int i = 0; i < exp.length(); i++)        {            char c = exp.charAt(i);                         if(c == ' ')            continue;                         // If the scanned character is an operand            // (number here),extract the number            // Push it to the stack.            else if(Character.isDigit(c))            {                int n = 0;                                 //extract the characters and store it in num                while(Character.isDigit(c))                {                    n = n*10 + (int)(c-'0');                    i++;                    c = exp.charAt(i);                }                i--;                 //push the number in stack                stack.push(n);            }                         // If the scanned character is an operator, pop two            // elements from stack apply the operator            else            {                int val1 = stack.pop();                int val2 = stack.pop();                                 switch(c)                {                    case '+':                    stack.push(val2+val1);                    break;                                         case '-':                    stack.push(val2- val1);                    break;                                         case '/':                    stack.push(val2/val1);                    break;                                         case '*':                    stack.push(val2*val1);                    break;            }            }        }        return stack.pop();    }         // Driver program to test above functions    public static void main(String[] args)    {        String exp = "100 200 + 2 / 5 * 7 +";        System.out.println(evaluatePostfix(exp));    }} // This code is contributed by Arnab Kundu
# Python program to evaluate value of a postfix# expression with integers containing multiple digits class evalpostfix:    def __init__(self):        self.stack =[]        self.top =-1    def pop(self):        if self.top ==-1:            return        else:            self.top-= 1            return self.stack.pop()    def push(self, i):        self.top+= 1        self.stack.append(i)     def centralfunc(self, ab):        for i in ab:             # if the component of the list is an integer            try:                self.push(int(i))            # if the component of the list is not an integer,            # it must be an operator. Using ValueError, we can            # evaluate components of the list other than type int            except ValueError:                val1 = self.pop()                val2 = self.pop()                 # switch statement to perform operation                switcher ={'+':val2 + val1, '-':val2-val1, '*':val2 * val1, '/':val2 / val1, '^':val2**val1}                self.push(switcher.get(i))        return int(self.pop()) str ='100 200 + 2 / 5 * 7 +' # splitting the given string to obtain# integers and operators into a liststrconv = str.split(' ')obj = evalpostfix()print(obj.centralfunc(strconv)) # This code is contributed by Amarnath Reddy
// C# program to evaluate value of a postfix// expression having multiple digit operandsusing System;using System.Collections.Generic; class GFG{// Method to evaluate value of// a postfix expressionpublic static int evaluatePostfix(string exp){    // create a stack    Stack<int> stack = new Stack<int>();     // Scan all characters one by one    for (int i = 0; i < exp.Length; i++)    {        char c = exp[i];         if (c == ' ')        {            continue;        }         // If the scanned character is an         // operand (number here),extract        // the number. Push it to the stack.        else if (char.IsDigit(c))        {            int n = 0;             // extract the characters and            // store it in num            while (char.IsDigit(c))            {                n = n * 10 + (int)(c - '0');                i++;                c = exp[i];            }            i--;             // push the number in stack            stack.Push(n);        }         // If the scanned character is        // an operator, pop two elements        // from stack apply the operator        else        {            int val1 = stack.Pop();            int val2 = stack.Pop();             switch (c)            {                case '+':                stack.Push(val2 + val1);                break;                 case '-':                stack.Push(val2 - val1);                break;                 case '/':                stack.Push(val2 / val1);                break;                 case '*':                stack.Push(val2 * val1);                break;            }        }    }    return stack.Pop();} // Driver Codepublic static void Main(string[] args){    string exp = "100 200 + 2 / 5 * 7 +";    Console.WriteLine(evaluatePostfix(exp));}} // This code is contributed by Shrikant13
<script>    // Javascript program to evaluate value of a postfix    // expression having multiple digit operands         // Method to evaluate value of    // a postfix expression    function evaluatePostfix(exp)    {        // create a stack        let stack = [];         // Scan all characters one by one        for (let i = 0; i < exp.length; i++)        {            let c = exp[i];             if (c == ' ')            {                continue;            }             // If the scanned character is an            // operand (number here),extract            // the number. Push it to the stack.            else if (c >= '0' && c <= '9')            {                let n = 0;                 // extract the characters and                // store it in num                while (c >= '0' && c <= '9')                {                    n = n * 10 + (c - '0');                    i++;                    c = exp[i];                }                i--;                 // push the number in stack                stack.push(n);            }             // If the scanned character is            // an operator, pop two elements            // from stack apply the operator            else            {                let val1 = stack.pop();                let val2 = stack.pop();                 switch (c)                {                    case '+':                    stack.push(val2 + val1);                    break;                     case '-':                    stack.push(val2 - val1);                    break;                     case '/':                    stack.push(parseInt(val2 / val1, 10));                    break;                     case '*':                    stack.push(val2 * val1);                    break;                }            }        }        return stack.pop();    }         let exp = "100 200 + 2 / 5 * 7 +";    document.write(evaluatePostfix(exp)); // This code is contributed by decode2207.</script>
Output : 
757
YouTubeGeeksforGeeks500K subscribersStack | Set 4 (Evaluation of Postfix Expression) | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 11:44•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=_TGyjXjg04w" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
References: http://www.cs.nthu.edu.tw/~wkhon/ds/ds10/tutorial/tutorial2.pdfPlease write comments if you find anything incorrect, or you want to share more information about the topic discussed above 
andrew1234
SoumikMondal
shrikanth13
rathbhupendra
AmarnathReddy4
surindertarika1234
avanitrachhadiya2155
as5853535
decode2207
niharikatanwar61
amartyaghoshgfg
Amazon
expression-evaluation
Stack
Amazon
Stack
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Implement Stack using Queues
Reverse a stack using recursion
Iterative Depth First Traversal of Graph
Difference between Stack and Queue Data Structures
Largest Rectangular Area in a Histogram | Set 2
Maximum size rectangle binary sub-matrix with all 1s
Design a stack that supports getMin() in O(1) time and O(1) extra space
Iterative Postorder Traversal | Set 2 (Using One Stack)
Design and Implement Special Stack Data Structure | Added Space Optimized Version
Merge Overlapping Intervals