An Introduction to Linked Lists in Python
2 min readFeb 10, 2021
A linked list is a data structure used for storing a sequence of elements. It’s data with some structure (the sequence).
Implementation of Linked List
class LinkedList():
def __init__(self):
self.head = None
def append(self, value):
if self.head is None:
self.head = Node(value)
else:
current_node = self.head
while current_node.next is not None:
current_node = current_node.next
current_node.next = Node(value)
def show_elements(self):
current = self.head
while current is not None:
print(current.data)
current = current.next
def length(self):
result = 0
current = self.head
while current is not None:
result += 1
current = current.next
return result
def get_element(self, position):
i = 0
current = self.head
while current is not None:
if i == position:
return current.data
current = current.next
i += 1
return None
How to reverse a Linked List?
def reverse(l):
if l.head is None:
return
current_node = l.head
prev_node = None
while current_node is not None:
# Track the next node
next_node = current_node.next
# Modify the current node
current_node.next = prev_node
# Update prev and current
prev_node = current_node
current_node = next_node
l.head = prev_node
Real World Applications of Linked Lists
- Image viewer — Previous and next images are linked, hence can be accessed by next and previous button.
- Previous and next page in web browser — We can access previous and next url searched in web browser by pressing back and next button since, they are linked as linked list.
- Music Player — Songs in music player are linked to previous and next song. you can play songs either from starting or ending of the list.