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

Building an MCP Agent with UV, Python & mcp-use

Model Context Protocol (MCP) is an open protocol designed to enable AI agents to interact with external tools and data in a standardized way. MCP is composed of three components: server , client , and host . MCP host The MCP host acts as the interface between the user and the agent   (such as Claude Desktop or IDE) and plays the role of connecting to external tools or data through MCP clients and servers. Previously, Anthropic’s Claude Desktop was introduced as a host, but it required a separate desktop app, license, and API key management, leading to dependency on the Claude ecosystem.   mcp-use is an open-source Python/Node package that connects LangChain LLMs (e.g., GPT-4, Claude, Groq) to MCP servers in just six lines of code, eliminating dependencies and supporting multi-server and multi-model setups. MCP Client The MCP client manages the MCP protocol within the host and is responsible for connecting to MCP servers that provide the necessary functions for the ...

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings

How to Save and Retrieve a Vector Database using LangChain, FAISS, and Gemini Embeddings Efficient storage and retrieval of vector databases is foundational for building intelligent retrieval-augmented generation (RAG) systems using large language models (LLMs). In this guide, we’ll walk through a professional-grade Python implementation that utilizes LangChain with FAISS and Google Gemini Embeddings to store document embeddings and retrieve similar information. This setup is highly suitable for advanced machine learning (ML) and deep learning (DL) engineers who work with semantic search and retrieval pipelines. Why Vector Databases Matter in LLM Applications Traditional keyword-based search systems fall short when it comes to understanding semantic meaning. Vector databases store high-dimensional embeddings of text data, allowing for approximate nearest-neighbor (ANN) searches based on semantic similarity. These capabilities are critical in applications like: Question Ans...

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...