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

How to Fine-Tune LLaMA 3.2-1B-Instruct for Korean Instruction Tasks with LoRA and Hugging Face

LLaMA 3.2-1B-Instruct is a lightweight instruction-tuned language model released by Meta. It is designed to handle a wide range of instruction-based tasks with relatively low computational resources. Although the model was trained with multilingual capabilities, its performance on languages not included in its training set—such as Korean—is limited. This tutorial demonstrates how to fine-tune this open-source model on a Korean dataset using Hugging Face Transformers and PEFT (specifically LoRA), enabling it to better respond to Korean instructions. 1. Prerequisites Before running the example code below, ensure you have the following libraries installed: pip install torch transformers datasets peft accelerate mlflow huggingface_hub To use the LLaMA model or KoAlpaca datasets, you'll need a Hugging Face token. Additionally, you may need to handle potential CUDA Out-Of-Memory (OOM) errors. The following code takes care of both: from huggingface_hub import login login("y...

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

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