Created : January 27, 2021

Written in Python.

  • Linear data structure
  • LIFO (Last In First Out)
  • Insertion/Deletion: only on same end
  • Example

    • stacked plates
    • undo (Ctrl + z)

Basic Operations

  • push: Add an item.

    • If the stack is full → Overflow condition
    • append(item)
  • pop: Remove an item.

    • If the stack is empty → Underflow condition
    • pop()
  • peek or top: Return top element of stack.
  • isEmpty: Return true if stack is empty, else false.
  • size: Return the size of the stack

Big-O Complexity for Stack

  • Time complexity

    • Insertion/Deletion: O(1)
    • Access/Search: O(n)
  • Space complexity: O(n)


# Create stack class
class Stack:
  # Initialize
  def __init__(self):
    self.items = []

  # Push an item to the end
  def push(self, item):

  # Pop an item from the end
  def pop(self):
    # Check if stack is not empty
    if not self.isEmpty():
      return self.items.pop()
      print('Stack underflow')
  # Return top element of stack
  def peek(self):
    # Check if stack is not empty
    if not self.isEmpty():
      return self.items[-1]
      print('Stack underflow')

  # Check if stack is empty
  def isEmpty(self):
    return len(self.items) == 0

  # Return size of stack
  def size(self):
    return len(self.items)