Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an operator onto the stack.
DSA C++
stack.push([1]);Attempts:
3 left
💡 Hint
Common Mistakes
Using stack.pop() instead of push.
Using stack.top() which only returns the top element.
✗ Incorrect
We push the current operator character 'ch' onto the stack.
2fill in blank
mediumComplete the code to check if the stack is empty before accessing the top element.
DSA C++
if (!stack.[1]()) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using stack.pop() which removes elements.
Using stack.top() which returns the top element but does not check emptiness.
✗ Incorrect
We use stack.empty() to check if the stack is empty before accessing top.
3fill in blank
hardFix the error in the precedence comparison to correctly compare operator precedence.
DSA C++
while (!stack.empty() && precedence(stack.top()) [1] precedence(ch)) {
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<' or '<=' which causes incorrect order.
Using '==' which only checks equality.
✗ Incorrect
We pop from the stack while the top operator has precedence greater than or equal to the current operator.
4fill in blank
hardFill both blanks to correctly append operands and pop operators to the postfix string.
DSA C++
if (isalnum(ch)) { postfix += [1]; } else { postfix += stack.[2](); stack.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using stack.pop() to get the operator which returns void.
Appending stack.empty() which is a boolean.
✗ Incorrect
Operands are appended directly using 'ch'. Operators are appended from the top of the stack using stack.top() before popping.
5fill in blank
hardFill all three blanks to correctly define the precedence function for operators.
DSA C++
int precedence(char op) {
if (op == '+' || op == [1]) return 1;
if (op == '*' || op == [2]) return 2;
return [3];
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '%' instead of '-' or '/' in precedence.
Returning 1 or 2 for unknown operators.
✗ Incorrect
The function returns 1 for '+' and '-', 2 for '*' and '/', and 0 for others.
