📢 Too many exams? Don’t know which one suits you best? Book Your Free Expert 👉 call Now!


    Question

    A custom stack implementation has a pop() method that is

    supposed to remove and return the top element. However, when the stack is empty, calling pop() causes an error (e.g., IndexError if using a list, or NullPointerException if using a linked list without proper checks). What is the most fundamental debugging step to prevent this underflow error?
    A Ensure the push() method correctly adds elements. Correct Answer Incorrect Answer
    B Implement a peek() method to view the top element without removing it. Correct Answer Incorrect Answer
    C Add a check if not self.is_empty(): before attempting to access or remove an element. Correct Answer Incorrect Answer
    D Increase the initial capacity of the stack. Correct Answer Incorrect Answer
    E Use a try-except block around the pop() operation. Correct Answer Incorrect Answer

    Solution

    The correct answer is C

    Practice Next
    ask-question