Learn › Class 12 › Computer Science / Informatics Practices › File handling and data structures (stack)
The stack data structure
You will learn to
- Describe a stack and its last-in, first-out order
- Implement push, pop and peek with a Python list and handle underflow
- Convert infix expressions to postfix and evaluate postfix with a stack
Helpful to know first: Python lists and their methods; Functions in Python.
A stack is a list where items are added and removed at one end only, called the top. The last item pushed is the first one popped: last in, first out (LIFO).
Think of a pile of rotis on a plate. You add a new roti on top, and you also take one from the top.
Stack with a Python list
Push: stack.append(x). Pop: stack.pop() removes and returns the top. Peek: stack[-1]. Empty check: len(stack) == 0. Popping an empty stack is called underflow; pushing onto a full fixed-size stack is overflow.
Stacks are used for undo in editors, the back button in browsers, reversing a string, checking matched brackets and evaluating expressions.
In postfix notation the operator comes after its operands, so A + B * C becomes A B C * +. To evaluate postfix, push numbers. On an operator, pop two values, apply it and push the result.
Common mix-ups
Not quite: stack.pop(0) is the right way to pop a stack built with append().
Instead: append() adds at the end, so the top is the end. Use stack.pop() with no argument.
Not quite: In postfix, for a − b the first value popped is a.
Instead: The first value popped is the right operand b. Compute second-popped − first-popped.