Linked Lists in Python Implementation
In this post, I aim to define a linked list, discuss the various types of linked lists, outline their advantages and disadvantages compared to arrays, and provide an implementation of the main methods for a singly linked list in Python. These methods include adding a node at the end, adding a node at the beginning, inserting a node in the middle, reversing the linked list, retrieving a node by index, printing the list, and more.
What is Linked List ?
A linked list is a linear data structure that serves as a linear collection of data elements organized in nodes. Each node contains information about its data and a reference to the next node in the sequence. Unlike arrays, which store elements in contiguous memory locations, linked elements are scattered in memory and connected by links. Each element in a linked list is called a node, and each node consists of two parts:
- Data: The actual value stored in the node.
- Next: A reference to the next node in the list.
a linked list looks like:
Types of Linked Lists
There are two main types of linked lists:
- Singly linked list: Each node only points to the next node in the list, where nodes have links in a single direction.
- Doubly linked list: Each node points to both the next and previous nodes in the list, where nodes have links to both the next and previous items.
How to Build a Singly Linked List in Python:
To construct a Singly Linked List in Python, the initial step involves creating a class to construct a node. Each item within the linked list acts as an individual object capable of holding any desired information. Additionally, it identifies the subsequent item in the linked list. Consequently, it is imperative for each node to possess an attribute that references or stores the contained information and another attribute that points to the following node in the linked list.
class Node:
def __init__(self, value):
self.value = value
self.next = NoneWe have value and next attributes that correspond to the data that the node holds, while also pointing to the next node in the linked list.
Get Worash Abocherugn’s stories in your inbox
Join Medium for free to get updates from this writer.
The second step involves creating a LinkedList class and initializing it with attributes such as head, tail, and length. Initially, we’ll create an empty linked list, allowing us to commence with both an empty head and tail. This approach eliminates the need for checking the existence of a head and tail during the initial creation of a linked list instance. Additionally, including a length attribute facilitates the addition or removal of items by incrementing or decrementing this count accordingly.
class LinkedList:
def __init__(self):
self.head= None
self.tail = None
self.length = 01. Adding Node to the End of a Singly Linked List:
Adding items to the end of a linked list is a fundamental operation. This insert_last method appends a new node containing the provided value to the end of the linked list. If the list is empty, it sets both the head and tail to the new node. If the list is not empty, it attaches the new node to the current tail and updates the tail reference to the newly added node. Finally, it increments the length of the linked list and returns the newly added node.
# insert data at the end of the list -> push
def insert_last(self, value):
new_node = Node(value)
if not self.head:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
return new_node2. Removing node from the End of a Singly Linked List:
There are two primary approaches to remove items from the end of a linked list in Python:
- Traversing the List: This method involves iterating through the list until you reach the second-to-last node. Once there, you can simply set its next pointer to
None.
2. Tail Pointer: This method involves maintaining a separate pointer to the last node of the list, often called the “tail” pointer. This allows for faster removal of the last node, as you don’t need to traverse the entire list. I provide implementation,aims to implement a method remove_last() within a linked list class. This method is responsible for deleting a node from the end of the linked list.:
# delete node from the end of the linked list -> pop
def remove_last(self):
if self.head is None: # if the list is empty
return "The list is empty, can't remove."
current = self.head
new_tail = None
while current.next is not None: # traverse the list to get the new tail
new_tail = current
current = current.next
if new_tail is None: # if the list has only one node
self.head = None
self.tail =None
else:
new_tail.next = None
self.tail = new_tail
self.length -= 1
return current3. Inserting a Node at the Beginning of a Singly Linked List:
Inserting a node at the beginning of a linked list is a fundamental operation in Python. The prepend() method adds a new node to the beginning of the linked list by creating a new node, updating pointers to connect it to the existing list (if any), and making it the new head of the list. This implementation efficiently handles scenarios where the list is empty or contains elements.
# insert node at the beging of the list => prepend
def prepend(self, value):
new_node = Node(value)
if not self.head and self.length == 0: # if the list is empty
self.head = new_node
self.tail = new_node
else:
new_node.next = self.head
self.head = new_node
self.length += 1
return new_nodeTime Complexity of prepend method is Inserting a node at the beginning of a linked list has a time complexity of O(1), constant time. This is because we only need to update a few pointers and don’t need to traverse the list.
4. Removing the First Node from a Singly Linked List:
Removing the first node from a linked list requires updating the head pointer and potentially freeing the memory allocated to the first node.
# remove the first node from the list
def remove_first(self):
if self.head is None and self.length == 0: # if the list is empty
return "The list is empty, can't remove."
removed_node = self.head
self.head = removed_node.next
removed_node.next = None
self.length -= 1
return removed_node.value # return the value of removed node5. Getting a Node at Specific Index from a Singly Linked List:
Accessing a specific node by index in a linked list requires iterating through the nodes from the head until reaching the desired position. Unlike arrays that store elements in contiguous memory, allowing direct access by index, linked lists involve sequential traversal from the beginning to the desired index, which could take linear time based on the index’s position. This means linked lists have O(n) time complexity for accessing elements by index, where ’n’ is the index position.
# get the node at specific index from list => get_at_index.
def get_at_index(self, index):
try:
if index < 0 or index >= self.length:
raise IndexError("No node at: " + str(index))
count = 0
current = self.head
while count != index:
current = current.next
count += 1
return current
except IndexError as err:
print(f"{err}")
return None6. Inserting a Node at a Specific Index in a Singly Linked List:
Inserting a node at a specific index in a linked list involves navigating to the desired position (the node before the intended insertion point) and adjusting the pointers to incorporate the new node into the sequence. It requires modifying the next pointers of the nodes to connect the new node in between the previous node (at index - 1) and the subsequent node.
# insert node at specific index
def add_at_index(self, index, value):
try:
inserted_node = None
if index < 0 or index > self.length:
raise IndexError("can't add at index: " + str(index))
elif index == 0:
inserted_node = self.prepend(value)
elif index == self.length:
inserted_node = self.insert_last(value)
else:
inserted_node = Node(value)
prev_node = self.get_at_index(index-1)
inserted_node.next = prev_node.next
prev_node.next = inserted_node
self.length += 1
return inserted_node
except IndexError as err:
return errThe above implementation manages various insertion scenarios, such as insertion at the start, end, or within the middle of the list, ensuring appropriate connections between nodes and updating the list’s length accordingly.
7. Updating a Node Value at Specific Index in a Singly Linked List:
Updating the value of a node at a specific index in a linked list entails traversing the list until the target node is reached and then modifying its value.
# update the value of the node at specific index list. => update_at_index
def update_at_index(self,index, value):
try:
node = self.get_at_index(index)
if node is not None:
node.value = value
return node
else:
raise IndexError("Node is not found at: " + str(index))
except Exception as error:
return errorThe update_at_index() method in a linked list traverses the list until it reaches the desired index, retrieving the node at that position. Upon locating the node, it modifies the node's value with the provided new value. This process ensures that the value of the node at the specified index is successfully updated, provided the index is within the valid range of the linked list.
8. Removing a Node from a Specific Index in a Singly Linked List:
Removing a node from a specific index in a linked list involves effectively handles different scenarios for removing nodes at specific indices within the linked list. It performs the removal by adjusting the pointers to reconfigure the linked list structure and appropriately manages memory deallocation to maintain data integrity.
def remove_at_index(self, index):
if index < 0 or index >= self.length or self.length == 0:
return False
elif index == 0:
self.remove_first()
return True
elif index == self.length - 1:
self.remove_last()
return True
else:
prev_node = self.get_at_index(index - 1)
temp = prev_node.next
prev_node.next = temp.next
temp = None
self.length -= 1
return True9. Printing a Singly Linked List:
Printing a linked list in Python involves navigating through the list and accessing the data stored in each node. This traversal begins from the head of the list and continues until the end, printing the value or any relevant information associated with each node during the iteration.
# print list => print_list
def print_list(self):
if self.head is None:
print("the list is empty, please add some")
temp = self.head
print("the length of the list is:", self.length)
while temp is not None:
print("Node value is: ", temp.value)
temp = temp.next10. Reversing a Singly Linked List:
Reversing a linked list involves rearranging the nodes in such a way that the order of elements is reversed.
# reverse list => reverse
def reverse(self):
if self.length == 0 or self.length == 1:
print("The list cannot be reversed")
return False
temp = self.head
self.head = self.tail
self.tail = temp
after = None
prev = None
for i in range(self.length):
after = temp.next
temp.next = prev
prev = temp
temp = after
return TrueThe reverse() method accomplishes this by altering the pointers of the nodes in a systematic manner. It initializes pointers and iterates through the list, rearranging the pointers to reverse the sequence of nodes.
Linked Lists Advantages over Python list:
- Dynamic size: Unlike arrays, whose size is fixed at creation, linked lists can grow or shrink dynamically as needed. This makes them ideal for situations where the data size is unpredictable.
- Efficient insertion and deletion: Inserting or deleting elements in the middle of a linked list is much faster than in an array. This is because there’s no need to shift other elements.
- No memory fragmentation: Linked lists don’t suffer from memory fragmentation like arrays. Memory is allocated only when needed for new nodes, reducing wasted space.
Linked Lists Disadvantages :
- Random access is slow: Accessing a specific element by index is slower than in an array. You need to traverse the list from the beginning to reach the desired element.
- Extra memory overhead: Each node in a linked list requires memory for both the data and the next pointer, which can be inefficient for storing large amounts of simple data.
Conclusion:
In this comprehensive guide, the article provides insights into the fundamental concepts of linked lists:
- Introduction to Linked Lists: Defines linked lists as linear data structures comprising nodes that contain data and references to the next nodes.
- Types of Linked Lists: Explains the two main types, namely singly linked lists and doubly linked lists, based on the direction of the node connections.
- Constructing a Singly Linked List in Python: Demonstrates the process by creating a
Nodeclass to represent individual elements and aLinkedListclass to manage the structure.
The article elaborates on essential operations:
- Adding and Removing Nodes: Describes how to add nodes to the beginning and end of the list, remove nodes from the beginning and end, and insert or remove nodes at specific indices.
- Accessing and Modifying Nodes: Covers methods to retrieve nodes by index and update their values.
- Printing and Reversing the List: Illustrates how to print the list and reverse its order using iterative techniques.
https://github.com/worashf/python-projects/blob/main/linked-list-implementation/linked_list.py






