Table of Contents
A stack is a linear data structure that follows the LIFO rule of handling elements stored in it. It has a few basic operations such as PUSH, POP, and PEEK.
Using a stack we implement various things like the undo and redo operation. One common type of questions asked around Stack are related to Infix to Postfix/Prefix conversion of expressions.
Postfix expressions
Infix expression -
Corresponding Postfix expression -
Infix to Postfix
Steps of conversion -
- Scan the infix expression from left to right, one character at a time and store the current character as
curr. Use a stackSto keep track of operator precedence and a variableYfor the output expression. - If
curris an operand,PUSH(curr, Y), else - If
curris a bracket then,- If
curris an opening bracket,PUSH(curr, S), else - If
curris a closing bracket,POP(S)untilSEEK(S)is an opening bracket andPOP(S)once more to remove that too. Basically, keep popping until the operators in the enclosed expression are removed from the stack.
- If
- If
curris an operator then,- If
SEEK(S) >= curr, thenPOP(S)untilSEEK(S) <= curr, else - If
SEEK(S) < curr, thenPUSH(curr, S).
- If
- If
curris$/EOF(end of expression)POP(S)until the stack is empty.
Evaluating Postfix expressions
- Scan from left to right.
- Push any operand onto a stack.
- If the current character is an operator,
s1=POP(S); s2=POP(S). Performs2 op s1and push the output back on the stack. - Keep doing this until the stack is empty.
Infix to Prefix
Infix expression -
Corresponding Prefix expression -
Steps of conversion -
- Scan the infix expression from right to left, one character at a time and store the current character as
curr. Use a stackSto keep track of operator precedence and a variableYfor the output expression. - If
curris an operand,PUSH(curr, Y), else - If
curris a bracket then,- If
curris a closing bracket,PUSH(curr, S), else - If
curris an opening bracket,POP(S)untilSEEK(S)is a closing bracket andPOP(S)once more to remove that too. Basically, keep popping until the operators in the enclosed expression are removed from the stack.
- If
- If
curris an operator then,- If
SEEK(S) > curr, thenPOP(S)untilSEEK(S) >= curr, else - If
SEEK(S) <= curr, thenPUSH(curr, S).
- If
- If
curris$/EOF(end of expression)POP(S)until the stack is empty. - Reverse
Yto someZ.Zis the resultant prefix expression.
Evaluating Prefix expressions
- Scan from right to left.
- Push any operand onto a stack.
- If the current character is an operator,
s1=POP(S); s2=POP(S)and performs1 op s2. Push the output back on the stack. - Keep doing this until the stack is empty.