Data Structures - Complete Explanation
with Examples
1. Arrays
An array is a collection of elements identified by index or key. It stores elements of the same
data type in contiguous memory locations.
Example:
Python Example - Find Maximum Element in Array:
arr = [3, 5, 1, 2, 4]
max_val = max(arr)
print("Maximum element:", max_val)
2. Strings
Strings are arrays of characters. Strings in Python are immutable.
Example:
Python Example - Reverse a String:
s = 'hello'
reversed_s = s[::-1]
print("Reversed String:", reversed_s)
3. Linked Lists
A linked list is a linear data structure where elements are stored in nodes with pointers to
the next node.
Example:
Python Example - Singly Linked List Implementation:
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 = self.head
while last.next:
last = last.next
last.next = new_node
def display(self):
curr = self.head
while curr:
print(curr.data, end=' -> ')
curr = curr.next
ll = LinkedList()
ll.append(10)
ll.append(20)
ll.display()
4. Stacks and Queues
Stacks follow Last In First Out (LIFO), Queues follow First In First Out (FIFO).
Stack Example (Python List):
stack = []
stack.append(1)
stack.append(2)
print(stack.pop()) # Output: 2
Queue Example (collections.deque):
from collections import deque
queue = deque()
queue.append(1)
queue.append(2)
print(queue.popleft()) # Output: 1
5. Trees (Binary Tree)
A tree is a non-linear data structure with a root node and subtrees of children.
Binary Tree: each node has at most two children.
Example - Inorder Traversal:
class Node:
def __init__(self, key):
self.left = None
self.right = None
self.val = key
def inorder(root):
if root:
inorder(root.left)
print(root.val)
inorder(root.right)
root = Node(1)
root.left = Node(2)
root.right = Node(3)
inorder(root)