Log In Sign Up
Day 11

Day 11: Introduction to Stacks

11/60 Days

Introduction to Stacks #

Welcome to Day 11 of our 60 Days of Coding Algorithm Challenge! Today, we’ll explore stacks, a fundamental data structure in computer science that follows the Last-In-First-Out (LIFO) principle.

What is a Stack? #

A stack is a linear data structure that follows a particular order in which operations are performed. The order may be LIFO(Last In First Out) or FILO(First In Last Out). Real-life examples include a stack of plates or a pile of books.

Basic Operations of a Stack #

  1. Push: Adds an element to the top of the stack
  2. Pop: Removes the top element from the stack
  3. Peek or Top: Returns the top element of the stack without removing it
  4. isEmpty: Returns true if the stack is empty, else false

Implementing a Stack in Python #

We can implement a stack using a Python list or create a custom class. Let’s implement both:

Using a Python List #

 1class Stack:
 2    def __init__(self):
 3        self.items = []
 4
 5    def is_empty(self):
 6        return len(self.items) == 0
 7
 8    def push(self, item):
 9        self.items.append(item)
10
11    def pop(self):
12        if not self.is_empty():
13            return self …