A stack is a Last-In-First-Out (LIFO) container: the last item pushed is the first one popped. It powers undo history, call stacks, and backtracking.
Complete the Stack class backed by a Python list. push, is_empty, and size are done. Implement pop (return the top item and remove it, or None if empty) and peek (return the top item without removing it, or None if empty).
class Stack:
def __init__(self):
self._data = []
def push(self, x):
self._data.append(x)
def pop(self):
"""Remove and return the top item, or None if the stack is empty."""
# TODO: return the most recently pushed item (LIFO), or None if empty
pass
def peek(self):
"""Return the top item without removing it, or None if empty."""
# TODO: return the top item without removing it, or None if empty
pass
def is_empty(self):
return len(self._data) == 0
def size(self):
return len(self._data)The editor and the test runner need a wide screen. Open this page on a desktop browser and your progress will be waiting.
A stack is a Last-In-First-Out (LIFO) container: the last item pushed is the first one popped. It powers undo history, call stacks, and backtracking.
Complete the Stack class backed by a Python list. push, is_empty, and size are done. Implement pop (return the top item and remove it, or None if empty) and peek (return the top item without removing it, or None if empty).
Press Run Tests or ββ© to check your solution.