Skip to main content

Understanding Queue and Stack in Data Structures

Data structures are fundamental concepts in computer science that help organize, manage, and store data efficiently. Two of the most basic and essential data structures are Queue and Stack. This article provides an in-depth explanation of their characteristics, Python implementation from scratch, and examples using Python's built-in libraries.


1. Stack (LIFO - Last In, First Out)

Stack is a linear data structure that follows the Last In, First Out (LIFO) principle. This means the last element added to the stack is the first one to be removed.

Characteristics of a Stack

  • Insertion (push) and removal (pop) happen at the same end, called the top of the stack.
  • Access to elements is restricted to the top of the stack only.
  • Common operations:
    • push(item): Add an item to the top.
    • pop(): Remove the top item.
    • peek(): View the top item without removing it.
    • is_empty(): Check if the stack is empty.

Python Implementation (From Scratch)

class Stack:
    def __init__(self):
        self.items = []

    def push(self, item):
        self.items.append(item)

    def pop(self):
        if not self.is_empty():
            return self.items.pop()
        raise IndexError("Pop from an empty stack")

    def peek(self):
        if not self.is_empty():
            return self.items[-1]
        raise IndexError("Peek from an empty stack")

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

# Example Usage
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
print(stack.pop())  # Output: 3
print(stack.peek()) # Output: 2

Python Built-in Library Example (Using List)

# Using Python's list as a stack
stack = []
stack.append(1)
stack.append(2)
stack.append(3)

print(stack.pop())  # Output: 3
print(stack[-1])    # Peek at the top element, Output: 2

2. Queue (FIFO - First In, First Out)

Queue is a linear data structure that follows the First In, First Out (FIFO) principle. This means the first element added to the queue will be the first one to be removed.

Characteristics of a Queue

  • Insertion (enqueue) happens at the rear end, and removal (dequeue) happens from the front end.
  • Elements are processed in the order they were added.
  • Common operations:
    • enqueue(item): Add an item to the rear.
    • dequeue(): Remove the item from the front.
    • peek(): View the front item without removing it.
    • is_empty(): Check if the queue is empty.

Python Implementation (From Scratch)

class Queue:
    def __init__(self):
        self.items = []

    def enqueue(self, item):
        self.items.append(item)

    def dequeue(self):
        if not self.is_empty():
            return self.items.pop(0)
        raise IndexError("Dequeue from an empty queue")

    def peek(self):
        if not self.is_empty():
            return self.items[0]
        raise IndexError("Peek from an empty queue")

    def is_empty(self):
        return len(self.items) == 0

    def size(self):
        return len(self.items)

# Example Usage
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.enqueue(3)
print(queue.dequeue())  # Output: 1
print(queue.peek())     # Output: 2

Python Built-in Library Example (Using collections.deque)

from collections import deque

# Using deque as a queue
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)

print(queue.popleft())  # Output: 1
print(queue[0])         # Peek at the front element, Output: 2

3. Summary: Stack vs Queue

FeatureStackQueue
PrincipleLIFO (Last In, First Out)FIFO (First In, First Out)
Primary OperationsPush, Pop, PeekEnqueue, Dequeue, Peek
Access PointTopFront and Rear
Common Python Toollistcollections.deque

References

Comments

Popular

Understanding SentencePiece: A Language-Independent Tokenizer for AI Engineers

In the realm of Natural Language Processing (NLP), tokenization plays a pivotal role in preparing text data for machine learning models. Traditional tokenization methods often rely on language-specific rules and pre-tokenized inputs, which can be limiting when dealing with diverse languages and scripts. Enter SentencePiece—a language-independent tokenizer and detokenizer designed to address these challenges and streamline the preprocessing pipeline for neural text processing systems. What is SentencePiece? SentencePiece is an open-source tokenizer and detokenizer developed by Google, tailored for neural-based text processing tasks such as Neural Machine Translation (NMT). Unlike conventional tokenizers that depend on whitespace and language-specific rules, SentencePiece treats the input text as a raw byte sequence, enabling it to process languages without explicit word boundaries, such as Japanese, Chinese, and Korean. This approach allows SentencePiece to train subword models di...

Mastering the Byte Pair Encoding (BPE) Tokenizer for NLP and LLMs

Byte Pair Encoding (BPE) is one of the most important and widely adopted subword tokenization algorithms in modern Natural Language Processing (NLP), especially in training Large Language Models (LLMs) like GPT. This guide provides a deep technical dive into how BPE works, compares it with other tokenizers like WordPiece and SentencePiece, and explains its practical implementation with Python code. This article is optimized for AI engineers building real-world models and systems. 1. What is Byte Pair Encoding? BPE was originally introduced as a data compression algorithm by Gage in 1994. It replaces the most frequent pair of bytes in a sequence with a single, unused byte. In 2015, Sennrich et al. adapted BPE for NLP to address the out-of-vocabulary (OOV) problem in neural machine translation. Instead of working with full words, BPE decomposes them into subword units that can be recombined to represent rare or unseen words. 2. Why Tokenization Matters in LLMs Tokenization is th...

Using Gemini API in LangChain: Step-by-Step Tutorial

What is LangChain and Why Use It? LangChain  is an open-source framework that simplifies the use of  Large Language Models (LLMs)  like OpenAI, Gemini (Google), and others by adding structure, tools, and memory to help build real-world applications such as chatbots, assistants, agents, or AI-enhanced software. Why Use LangChain for LLM Projects? Chainable Components : Easily build pipelines combining prompts, LLMs, tools, and memory. Multi-Model Support : Work with Gemini, OpenAI, Anthropic, Hugging Face, etc. Built-in Templates : Manage prompts more effectively. Supports Multi-Turn Chat : Manage complex interactions with memory and roles. Tool and API Integration : Let the model interact with external APIs or functions. Let's Walk Through the Code: Gemini + LangChain I will break the code into  4 main parts , each showcasing different features of LangChain and Gemini API. Part 1: Basic Gemini API Call Using LangChain import os from dotenv import load_dotenv load_dot...