Stack Operations with a List

50 min read Data Structure: Stack

This is a free course. Log in to run the code exercises and track your progress.

Stack Operations with a List

A data structure organises data so that it can be used efficiently. A stack is a linear structure in which elements are added and removed at only one end, the top. The last element pushed is the first one popped: LIFO (last in, first out), like a pile of plates.

  • PUSH: add an element on top. In Python: stack.append(x).
  • POP: remove and return the top element: stack.pop(). Popping an empty stack is an underflow.
  • PEEK (top): look at the top element without removing it: stack[-1].
  • isEmpty: len(stack) == 0.
def push(stack, item):
    stack.append(item)

def pop(stack):
    if not stack:
        return "Underflow"
    return stack.pop()

def peek(stack):
    return stack[-1] if stack else None

s = []
push(s, 10); push(s, 20); push(s, 30)
print(pop(s), peek(s), s)   # 30 20 [10, 20]

Uses of a stack: the Undo button, the browser's Back button, reversing a sequence, checking brackets, and Python's own record of which function called which.

Python exercise

Process stack commands, one per line, until END: PUSH x pushes x, POP pops and prints the top (or Underflow), PEEK prints the top without removing it (or Empty). At the end print the stack from top to bottom, separated by spaces, or Empty.

stack = []
while True:
    cmd = input().split()
    if cmd[0] == "END":
        break
    if cmd[0] == "PUSH":
        stack.append(cmd[1])
    # handle POP and PEEK
print(" ".join(stack) if stack else "Empty")  # print from the top down

Log in to edit and run this code.