In a previous post, I introduced data structure including: What are data structures? Classification of data structure.
In this article, I will show you how to set up a singly linked list algorithm in Python.
A linked list is a fundamental data structure in computer science. It consists of nodes where each node contains data and a reference (link) to the next node in the sequence. This allows for dynamic memory allocation and efficient insertion and deletion operations compared to arrays.
A singly linked list is a linear data structure in which the elements are not stored in contiguous memory locations and each element is connected only to its next element using a pointer.
You can clone the source code here to follow it easier.
mkdir singly_linked_list cd singly_linked_list vi singly_linked_list.py
class Node: def __init__(self, data: int) -> None: self.data = data self.next = None
class SinglyLinkedList: def __init__(self) -> None: self.head = None
There are three types:
Insert a node at the beginning
Step to insert:
def insert_at_head(self, data: int): new_node = Node(data) new_node.next = self.head self.head = new_node
Insert a node at the end
Step to insert:
def insert_at_tail(self, data: int): node_len = self.get_len() if (node_len == 0): return self.insert_at_head(data) new_node = Node(data) current = self.head while current.next: current = current.next current.next = new_node
Insert a node at a given position
Step to insert:
def insert_at_index(self, data: int, index: int): if (index < 0): return None if (index == 0): return self.insert_at_head(data) node_len = self.get_len() if (index >= node_len): return self.insert_at_tail(data) new_node = Node(data) prev_node = self.get_node_at_index(index - 1) new_node.next = prev_node.next prev_node.next = new_node
There are three types:
Delete a node at the beginning
Step to delete:
def delete_first_node(self): if (self.head is None): return None new_first_node = self.head.next self.head = new_first_node
Delete a node at the end
Step to delete:
def delete_last_node(self): if (self.head is None or self.head.next is None): return self.delete_first_node() node_len = self.get_len() prev_node = self.get_node_at_index(node_len - 2) prev_node.next = None
Delete a node at a given position
Step to delete:
def delete_node_at_index(self, index: int): if (self.head is None or index < 0): return None if (index == 0): return self.delete_first_node() if (index >= self.get_len() - 1): return self.delete_last_node() prev_node = self.get_node_at_index(index - 1) del_node = self.get_node_at_index(index) next_node = del_node.next prev_node.next = next_node
In this article, I introduced linked lists and the algorithm settings for a single-linked list in Python.
Hope this article will be useful to you.
My door is always open if you have any comments.
Continue, You want to be able to setup a doubly linked list in Python that I will show you in the next article Doubly linked list.
Document references: