A linked list is a linear data structure where each element is a separate object called a node. Each node contains data and a reference (or link) to the next node in the sequence. Linked lists are useful when you need to insert or delete elements at any position efficiently.
A stack is a Last - In - First - Out (LIFO) data structure. Elements are added and removed from the top of the stack. Stacks are commonly used in algorithms such as expression evaluation and backtracking.
A queue is a First - In - First - Out (FIFO) data structure. Elements are added at the rear and removed from the front. Queues are used in scenarios like task scheduling and breadth - first search algorithms.
A tree is a hierarchical data structure with a root node and zero or more sub - trees. Each node can have zero or more child nodes. Binary trees, where each node has at most two children, are a common type of tree used in searching and sorting algorithms.
A graph is a non - linear data structure consisting of vertices (nodes) and edges that connect these vertices. Graphs are used to represent relationships between objects, such as social networks or transportation networks.
In Python, we can implement a simple singly linked list as follows:
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last_node = self.head
while last_node.next:
last_node = last_node.next
last_node.next = new_node
def display(self):
elements = []
current = self.head
while current:
elements.append(current.data)
current = current.next
print(elements)
llist = LinkedList()
llist.append(1)
llist.append(2)
llist.append(3)
llist.display()
We can use Python’s built - in list as a stack:
stack = []
stack.append(1)
stack.append(2)
stack.append(3)
print(stack.pop())
Python’s collections
module provides the deque
class which can be used as a queue:
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
queue.append(3)
print(queue.popleft())
Here is a simple implementation of a binary tree:
class TreeNode:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
We can represent a graph using a dictionary in Python:
graph = {
'A': ['B', 'C'],
'B': ['A', 'D'],
'C': ['A', 'D'],
'D': ['B', 'C']
}
stack_of_operations
instead of s
.Advanced data structures in Python provide powerful tools to solve complex problems efficiently. By understanding the fundamental concepts, usage methods, common practices, and best practices of linked lists, stacks, queues, trees, and graphs, Python programmers can enhance their problem - solving skills and write more optimized code. Whether you are working on data science projects, web development, or algorithm design, these advanced data structures will prove to be invaluable.