Presentation On Stack Data Structure and Its Applications: Name Department Roll No
Presentation On Stack Data Structure and Its Applications: Name Department Roll No
RECURSION IN STACKS
Delimiter Checking
Reverse a Data
1.2 If the character is an operator, pop the 2 top most elements from the stack and perform the
operation. Push the result back to the stack.
Once the expression is fully traversed, the element in the stack is the result.
We traverse the entire string exactly once. Also, we perform a maximum of 2n push/pop operations, which
means that an element goes into the stack and comes out of the stack(2n operations for n elements). This
results in a time complexity of O(n).
We use an auxiliary stack which can contain a maximum of N/2 elements. Hence, the space complexity of the
algorithm is O(N).
Step by Step Example
Given expression is: 5 + 3 * 7.
Check especially for a condition when the operator at the top of the stack and the scanned
operator both are ‘^‘. In this condition, the precedence of the scanned operator is higher due
to its right associativity. So it will be pushed into the operator stack.
In all the other cases when the top of the operator stack is the same as the scanned operator,
then pop the operator from the stack because of left associativity due to which the scanned
operator has less precedence.
Else, Pop all the operators from the stack which are greater than or equal to in precedence
than that of the scanned operator.
After doing that Push the scanned operator to the stack. (If you encounter parenthesis while
popping then stop there and push the scanned operator in the stack.)
If the scanned character is a ‘(‘, push it to the stack.
If the scanned character is a ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.
Repeat steps 2-5 until the infix expression is scanned.
Once the scanning is over, Pop the stack and add the operators in the postfix expression
until it is not empty.
Finally, print the postfix expression.
Infix to postfix with illustration
Thank you