4. The following code tries to implement a pop operation on a linked list stack but causes an error:
def pop(self):
if self.top is None:
return None
value = self.top.data
self.top = self.top.next
return value
stack = Stack()
stack.pop()
What is the likely cause of the error?
medium
A. pop method returns wrong value
B. pop method does not update top pointer
C. Stack class is not defined or missing __init__ method
D. No error; code works fine
Solution
Step 1: Analyze code snippet
pop method looks correct logically, but Stack class is not shown or initialized.
Step 2: Identify error cause
Calling stack = Stack() without defining Stack class or __init__ causes NameError or AttributeError.
Final Answer:
Stack class is not defined or missing __init__ method -> Option C
Quick Check:
Undefined class = A [OK]
Hint: Check if class and constructor exist before method calls [OK]
Common Mistakes:
Assuming pop method logic is wrong
Ignoring missing class definition
Thinking pop doesn't update top
5. You want to implement a stack for a program that requires frequent push and pop operations but has very limited memory. Which implementation is better and why?
Array stack with fixed size or linked list stack?
hard
A. Linked list stack, because it is simpler to implement
B. Array stack, because it uses contiguous memory and less overhead
C. Array stack, because it allows faster random access
D. Linked list stack, because it uses dynamic memory and no wasted space
Solution
Step 1: Consider memory overhead
Linked list nodes store extra pointers, increasing memory per element.
Step 2: Compare array memory usage
Array stack uses contiguous memory without pointer overhead, so less memory per element if size is fixed.
Step 3: Evaluate suitability for limited memory
Fixed size array stack is better when memory is limited and size is known.
Final Answer:
Array stack, because it uses contiguous memory and less overhead -> Option B