Open In App

Evaluation of Postfix Expression

Last Updated : 28 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Given a postfix expression, the task is to evaluate the postfix expression. A Postfix expression is of the form "a b operator" ("a b +") i.e., a pair of operands is followed by an operator.

Examples:

Input: arr = ["2", "3", "1", "*", "+", "9", "-"]
Output: -4
Explanation: If the expression is converted into an infix expression, it will be 2 + (3 * 1) - 9 = 5 - 9 = -4.

Input: arr = ["100", "200", "+", "2", "/", "5", "*", "7", "+"]
Output: 757
Explanation: If the expression is converted into an infix expression, it will be ((100 + 200) / 2) * 5 + 7 = 150 * 5 + 7 = 757.

Approach: Using Stack

To evaluate a postfix expression we can use a stack. Idea is to iterate the expression from left to right and keep on storing the operands into a stack. Once an operator is received, pop the two topmost elements and evaluate them and push the result in the stack again.

Follow the steps mentioned below to evaluate postfix expression using stack:

  • Create a stack to store operands (values).
  • Scan the given expression from left to right and do the following for every element in array.
    • If the element is a number, push it into the stack.
    • 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.
  • When the expression is ended, the number in the stack is the final answer.

Illustration:

Consider the expression: arr = ["2", "3", "1", "*", "+", "9", "-"]


C++
// C++ program to evaluate value of a postfix
// expression Using Stack
#include <iostream>
#include <stack>
#include <vector>
using namespace std;

// Function to evaluate a postfix expression given as a vector of strings
int evaluatePostfix(vector<string>& arr) {
    stack<int> st;

    // Loop through each element in the vector
    for (string token : arr) {
        
        // If it's an operand (number), push it onto
        // the stack
        if (isdigit(token[0]) || (token.size() > 1 && token[0] == '-')) {
            st.push(stoi(token));
        } 
        
        // Otherwise, it must be an operator
        else {
            int val1 = st.top();
            st.pop();
            int val2 = st.top();
            st.pop();

            if (token == "+") {
                st.push(val2 + val1);
            } else if (token == "-") {
                st.push(val2 - val1);
            } else if (token == "*") {
                st.push(val2 * val1);
            } else if (token == "/") {
                st.push(val2 / val1);
            }
        }
    }
    return st.top();
}

int main() {
    vector<string> arr = {"2", "3", "1", "*", "+", "9", "-"};
    cout << evaluatePostfix(arr) << endl; 
    return 0;
}
C
// C program to evaluate value of a postfix
// expression having multiple digit operands

#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
#include <string.h>

#define MAX_SIZE 100

// Stack structure
typedef struct {
    int data[MAX_SIZE];
    int top;
} Stack;

// Function to initialize stack
void initStack(Stack *stack) {
    stack->top = -1;
}

// Function to push an element onto the stack
void push(Stack *stack, int value) {
    if (stack->top < MAX_SIZE - 1) {
        stack->data[++stack->top] = value;
    }
}

// Function to pop an element from the stack
int pop(Stack *stack) {
    if (stack->top >= 0) {
        return stack->data[stack->top--];
    }
    return 0; 
}

// Function to evaluate postfix expression 
// given as an array of strings
int evaluatePostfix(char *arr[], int size) {
    Stack stack;
    initStack(&stack);

    for (int i = 0; i < size; i++) {
        char *token = arr[i];

        // If token is a number, push it onto the stack
        if (isdigit(token[0]) || (token[0] == '-' && isdigit(token[1]))) {
            push(&stack, atoi(token));
        } 
        // Otherwise, it must be an operator
        else {
            int val1 = pop(&stack);
            int val2 = pop(&stack);

            if (strcmp(token, "+") == 0) {
                push(&stack, val2 + val1);
            } else if (strcmp(token, "-") == 0) {
                push(&stack, val2 - val1);
            } else if (strcmp(token, "*") == 0) {
                push(&stack, val2 * val1);
            } else if (strcmp(token, "/") == 0) {
                push(&stack, val2 / val1);
            }
        }
    }
    return pop(&stack);
}

int main() {
    char *arr[] = {"2", "3", "1", "*", "+", "9", "-"};
    int size = sizeof(arr) / sizeof(arr[0]);

    printf("%d\n", evaluatePostfix(arr, size)); 
    return 0;
}
Java
// Java program to evaluate value of a postfix
// expression Using Stack
import java.util.Stack;

 class GfG {
    
    // Function to evaluate postfix expression
    static int evaluatePostfix(String[] arr) {
        Stack<Integer> stack = new Stack<>();

        for (String token : arr) {
            
            // If the token is a number, push it onto the stack
            if (token.matches("-?\\d+")) {  
                stack.push(Integer.parseInt(token));
            } 
            
            // Otherwise, it must be an operator
            else {
                int val1 = stack.pop();
                int val2 = stack.pop();

                switch (token) {
                    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();
    }

    public static void main(String[] args) {
        String[] arr = {"2", "3", "1", "*", "+", "9", "-"};
        System.out.println(evaluatePostfix(arr)); 
    }
}
Python
# Python program to evaluate value of a postfix
# expression Using Stack
import math

# Function that returns evaluated value of a given postfix expression
def evaluatePostfix(arr: list[str]) -> int:
    stack = []

    for token in arr:
        # If token is a number, push it onto the stack
        if token.lstrip('-').isdigit():  
            stack.append(int(token))
        else:
            val1 = stack.pop()
            val2 = stack.pop()

            if token == "+":
                stack.append(val2 + val1)
            elif token == "-":
                stack.append(val2 - val1)
            elif token == "*":
                stack.append(val2 * val1)
            elif token == "/":
                stack.append(math.trunc(val2 / val1))

    return stack.pop()

if __name__ == "__main__":
    arr = ["2", "3", "1", "*", "+", "9", "-"]
    print(evaluatePostfix(arr))  
C#
// C# program to evaluate value of a postfix
// expression Using Stack
using System;
using System.Collections.Generic;

class GfG {
    // Function to evaluate postfix expression
    static int evaluatePostfix(string[] arr) {
        Stack<int> stack = new Stack<int>();

        foreach (string token in arr) {
            // If the token is a number, push it onto the stack
            if (int.TryParse(token, out int number)) {
                stack.Push(number);
            }
            else {
                int val1 = stack.Pop();
                int val2 = stack.Pop();

                switch (token) {
                    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();
    }

    static void Main() {
        string[] arr = { "2", "3", "1", "*", "+", "9", "-" };
        Console.WriteLine(evaluatePostfix(arr)); 
    }
}
JavaScript
// JavaScript program to evaluate value of a postfix
// expression Using Stack

// Function that returns evaluated value of a given postfix expression
function evaluatePostfix(arr) {
    let stack = [];

    for (let token of arr) {
        
        // If token is a number, push it onto the stack
        if (!isNaN(token)) {
            stack.push(Number(token));
        } else {
            let val1 = stack.pop();
            let val2 = stack.pop();

            switch (token) {
                case "+":
                    stack.push(val2 + val1);
                    break;
                case "-":
                    stack.push(val2 - val1);
                    break;
                case "*":
                    stack.push(val2 * val1);
                    break;
                case "/":
                    stack.push(Math.trunc(val2 / val1)); 
                    break;
            }
        }
    }
    return stack.pop();
}

// Driver Code 
const arr = ["2", "3", "1", "*", "+", "9", "-"];
console.log(evaluatePostfix(arr)); 

Output
-4

Time Complexity: O(n) 
Auxiliary Space: O(n)



Next Article
Practice Tags :

Similar Reads