Understanding Data Structures and Algorithms: Practical Coding Examples

Data structures and algorithms are fundamental to programming. Here are some practical examples to help you understand these concepts better.
1. Arrays and Linked Lists
pythonCopy code# Array example
arr = [1, 2, 3, 4, 5]
for num in arr:
print(num)
# Linked list example
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 print_list(self):
current = self.head
while current:
print(current.data)
current = current.next
ll = LinkedList()
ll.append(1)
ll.append(2)
ll.append(3)
ll.print_list()
2. Sorting Algorithms
pythonCopy code# Bubble sort example
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:", arr)




