Skip to content

alphaPlan · Data Structures, Algorithms & the Web · Cheat-sheet 03

Linear data structures

Learn a structure by its contract first, then use a stack for most recent first and a queue for first come, first served.

Ideas to remember

  1. 01An abstract data type is a contract: what operations it offers and how they behave, with no mention of how they are built.
  2. 02Code that relies only on the contract keeps working when the implementation changes; code that reaches inside the machinery breaks.
  3. 03A stack is LIFO: push puts an item on the top, pop takes the top item off, and items come out in reverse order of arrival.
  4. 04A queue is FIFO: enqueue adds at the back, dequeue removes from the front, so items leave in the order they arrived.
  5. 05The back button, undo and the call stack are stacks; a print queue, an event list and any fair waiting line are queues.
  6. 06A Python list serves as both: append and pop() make a stack, append and pop(0) make a queue.

Words

.append()
Push onto a stack, or enqueue at the back of a queue; both add at the end of the list.
.pop()
Removes and returns the last item, the top of the stack.
.pop(0)
Removes and returns the item at index 0, the front of the queue.
while stack:
Keeps popping until the stack is empty; the palindrome check rebuilds the word backwards this way.
record(team), points(team)
The whole abstract type of a scoreboard: give one point to a team, report how many points a team has; the dictionary behind them is the implementation.

Do this

  • When you meet a new structure, learn its contract first: what can I add, what can I take out, what can I ask, and in what order do things come back?
  • Describe the contract before writing a line of storage code, then choose an implementation.
  • Check with if stack: or if queue: before you pop, because popping an empty structure raises an error.
  • Ask which order is fair for your problem: newest first is a stack, oldest first is a queue.

Watch out

  • pop(0) on a list shifts every remaining item one place left, so its cost grows with the length; for a long queue use collections.deque and popleft().
  • Swap a queue for a stack in a waiting line and the last to arrive is served first, which no fair line would allow.
  • Code that cares how long an operation takes can tell implementations apart, even when the contract is the same.

Found something unclear, outdated or improvable? Suggest an improvement