28: Evaluate a postfix expression using a stack.
⏳⌚ 00:00:00

Question:-

Evaluate a postfix expression using a stack.
Example 1:
Input: str = “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.

Steps to solve:-

1. Stack data structure:-
A stack data structure is defined using a structure called Stack, which contains fields for the top of the stack, the stack's capacity, and an array to store stack elements.
The createStack function is used to create a new stack. It dynamically allocates memory for the stack and its array and initializes the top to -1.
The isEmpty function checks whether the stack is empty, i.e., if the top is -1.
The peek function returns the element at the top of the stack without removing it.
The pop function pops (removes and returns) the top element from the stack.
The push function pushes an element onto the stack.
The evaluatePostfix function takes a postfix expression as input and evaluates it. It initializes a stack with a capacity equal to the length of the expression.
It scans each character of the input expression one by one:
If the character is a digit, it's an operand, and it's pushed onto the stack as an integer. If the character is an operator (+, -, *, or /), it pops the top two elements from the stack, performs the operation, and pushes the result back onto the stack. Finally, the evaluatePostfix function returns the result, which is the value of the postfix expression.
2. main function:- In the main function, an example postfix expression "231*+9-" is provided as input to the evaluatePostfix function. The result is printed using printf.

solution->

View Code 1
Time Complexity = O(n)
Space Complexity = O(n)