An Introduction to Linked Lists in Python

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
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

  1. Image viewer — Previous and next images are linked, hence can be accessed by next and previous button.
  2. 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.
  3. 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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store