Abstract_Data_Types_ADTs
Abstract_Data_Types_ADTs
An Abstract Data Type (ADT) is a mathematical model for a data structure that defines the behavior
(operations) and properties (constraints) without specifying the implementation details. ADTs focus
on what operations are supported rather than how they are implemented.
Components of ADT
Data: Represents the data elements that the ADT works on.
Operations: Can be primitive (e.g., integers, floats) or composite (e.g., records, objects).
Constructor: Create and initialize the data structure.
Accessors: Retrieve data or properties without modifying the structure.
Mutators: Modify the data (e.g., insert, delete, or update elements).
Specifications: Describes the constraints or rules governing the behavior of the ADT.
Example: Stack ADT must follow LIFO (Last-In-First-Out) order.
2. Stack:
Data: Elements arranged in a LIFO order.
Operations:
Push (add element)
Pop (remove element)
Peek/Top (view the top element)
isEmpty (check if the stack is empty)
Example: Function call stack
3. Queue:
Data: Elements arranged in FIFO (First-In-First-Out) order.
Operations:
Enqueue (add element at the rear)
Dequeue (remove element from the front)
Peek/Front (view the front element)
isEmpty (check if the queue is empty)
Variations: Circular Queue, Priority Queue, Double-Ended Queue (Deque)
7. Graph:
Data: Nodes (vertices) connected by edges.
Operations:
Add/remove vertices
Add/remove edges
Check adjacency
Traverse (DFS, BFS)
Types: Directed, Undirected, Weighted
8. Priority Queue:
Data: Elements with associated priorities.
Operations:
Insert with priority
Remove highest/lowest priority element
Example: Task scheduling
Characteristics of ADTs
Encapsulation: Details of the implementation are hidden from the user.
Modularity: Implementation changes do not affect the user interface.
Abstraction: Focus on behavior rather than implementation.
Reusability: Can be implemented differently but used interchangeably.
ADT Implementations
ADTs are abstract concepts but are implemented using specific data structures in programming. For
example:
Stack: Implemented using arrays or linked lists.
Queue: Implemented using arrays, linked lists, or circular buffers.
Map: Implemented using hash tables, binary search trees, or skip lists.
Page 2
Abstract Data Types (ADTs) define what operations can be performed on a data structure and the
constraints/rules they follow. They do not specify how these operations are implemented. This
separation of abstraction (interface) and implementation enables flexibility and modularity in
software development.
Abstraction: The user only needs to know the interface (e.g., push and pop for a stack) and not
how
Encapsulation: The internal workings are hidden, which simplifies usage and reduces bugs due
to implementation changes.
1. Stack (LIFO)
Implementation using a list (array-based stack):
class Stack:
def __init__(self):
self.stack = []
def pop(self):
if not self.is_empty():
return self.stack.pop() # Remove from the top
raise IndexError("Pop from an empty stack")
def peek(self):
if not self.is_empty():
return self.stack[-1] # View the top element
raise IndexError("Peek from an empty stack")
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
Example Usage
stack = Stack()
stack.push(10)
stack.push(20)
print("Top Element:", stack.peek())
print("Popped:", stack.pop())
print("Stack Empty:", stack.is_empty())
2. Queue (FIFO)
Implementation using collections.deque (efficient for queues):
class Queue:
def __init__(self):
self.queue = deque()
Page 3
def enqueue(self, value):
self.queue.append(value) # Add to the rear
print(f"Enqueued: {value}")
def dequeue(self):
if not self.is_empty():
return self.queue.popleft() # Remove from the front
raise IndexError("Dequeue from an empty queue")
def peek(self):
if not self.is_empty():
return self.queue[0] # View the front element
raise IndexError("Peek from an empty queue")
def is_empty(self):
return len(self.queue) == 0
def size(self):
return len(self.queue)
Example Usage
queue = Queue()
queue.enqueue(5)
queue.enqueue(15)
print("Front Element:", queue.peek())
print("Dequeued:", queue.dequeue())
3. Map (Dictionary)
Implementation using Python's built-in dictionary:
class Map:
def __init__(self):
self.map = {}
def put(self, key, value):
self.map[key] = value
print(f"Inserted: ({key}: {value})")
Summary
ADTs provide a blueprint for organizing data.
Implementations depend on the programming language and specific requirements.
Understanding ADTs helps in making informed decisions for solving real-world problems.
2. Queue (FIFO)
Applications:
Task Scheduling: Used in CPU scheduling (e.g., Round Robin) and managing jobs in a print
queue.
Data Transmission: Manages packets in network routers and buffers for smooth data flow.
Customer Service: Ticket systems (e.g., banks or customer support) queue users for first-come-
first-served service.
Breadth-First Search (BFS): BFS in graphs uses a queue to explore nodes level by level.
4. Set
Applications:
Membership Testing: Quickly checks for the existence of an element (e.g., in dictionaries or spam
filters).
Removing Duplicates: Ensures uniqueness in a collection of elements.
Mathematical Operations: Union, intersection, and difference are widely used in database queries
and data analysis.
Geographical Applications: Tracks unique locations visited by a user or devices connected to a
network.
5. Map (Dictionary)
Applications:
Key-Value Storage: Used in caching systems, where keys are queries, and values are results.
Configuration Management: Stores settings for applications (e.g., JSON or YAML files).
Indexing and Searching: In search engines, maps index keywords to documents.
E-Commerce: Tracks inventory (product ID as key, stock quantity as value).
6. Graph
Applications:
Social Networks: Represents users as nodes and friendships as edges.
Web Crawling: Search engines model websites as graphs for crawling and ranking.
Route Optimization: Google Maps uses graphs to find the shortest path between locations.
Recommendation Systems: Models relationships (e.g., between users and products) to
recommend content.
Electrical Circuits: Represents connections between components.
Page 6
7. Priority Queue
Applications:
Task Scheduling: Operating systems prioritize tasks based on urgency.
Pathfinding Algorithms: Algorithms like Dijkstra's and A* use priority queues to determine the
shortest path.
Event-Driven Simulations: Simulates real-world events like traffic flow or stock market activities.
Data Compression: Huffman coding for lossless data compression uses priority queues.
8. Array/List
Applications:
Static Data Storage: Used for storing tabular data like spreadsheets.
Image Processing: Represents pixel data in image files.
Dynamic Programming: Stores intermediate results for optimization problems.
9. Linked List
Applications:
Dynamic Memory Allocation: Helps manage memory blocks that are created and released
dynamically.
Browser Cache: Implements least recently used (LRU) caches using doubly linked lists.
Music/Video Playlists: Represents songs or videos with forward and backward navigation.
Page 7